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.

gcc

Last visit:  3 years ago
Registered:  6 years ago
2.
By MikeMirzayanov, history, 2 years ago, In English
Welcome GNU G++23 14.2 (64 bit, msys2) <i><b>UPDATE:</b> Some time ago, there was news here that we supported C++23 by installing GCC 14 from the Winlibs project. It turned out that with this method of supporting C++23, some compatibility issues lead to significant performance drops in certain submissions. So, I tried another distribution for GCC 14: the MSYS2 project. It seems that this problem does not occur with it, and now there are no unexpected performance drops. Let's test this C++23 support option together!</i> Hello, Codeforces! Together with [user:Vladosiya,2024-08-22], we've added support for the 64-bit g++14 C++23. You can find it under the name `GNU G++23 14.2 (64 bit, msys2)`. If you're using Windows, you can easily install it via our minimalistic package manager, PBOX, by running the command `pbox install gcc14-64-msys2`. Thanks to the MSYS2 project! We used the distribution from the official package manager. Your solutions will be compiled using the following command line: `g++ -Wall -Wextra -...
UPDATE: Some time ago, there was news here that we supported C++23 by installing GCC 14

Full text and comments »

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

3.
By MikeMirzayanov, 5 years ago, In English
C++20 Is Released Hello, Codeforces. Please, welcome c++20 support on Codeforces. Yes, it is 64-bit. Thanks to Brecht Sanders: I used his distribution GCC-11.2.0-64 from https://winlibs.com/. If you have installed [PBOX](http://pbox.me/packages), you can add this compiler with the line `pbox install gcc11-64-winlibs`. Probably, a good idea is to add `C:\Programs\gcc11-64-winlibs\bin` into the PATH. More about PBOX you can read [here](https://codeforces.me/blog/entry/18274). I use the compilation command line similar to other GCC installations: `g++ -Wall -Wextra -Wconversion -static -DONLINE_JUDGE -Wl,--stack=268435456 -O2 -std=c++20 <source>`. The only differences are `-std=c++20` and `-Wall -Wextra -Wconversion` (I plan to use somehow such warnings in Polygon to suggest fixes in uploaded files). Now you can use c++20 in your solutions. I'm not sure there are many features useful in competitive programming. Probably, I'm wrong. For example, now you can write `vector v{vector{1, 2}};` inste...
Brecht Sanders: I used his distribution GCC-11.2.0-64 from https://winlibs.com/. If you have, his distribution GCC-11.2.0-64 from https://winlibs.com/., latest GCC compiler from MSYS2 is terribly slow in some cases. I don't want to use it here. Also, it, I use the compilation command line similar to other GCC installations: `g++ -Wall -Wextra

Full text and comments »

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

4.
By andreyv, 12 years ago, translation, In English
Catching silly mistakes with GCC As you know, the C++ language assumes that the programmer is always correct. Therefore C++ compilers don't add additional checks to the program, such as checks for null pointer dereference or out-of-bounds array access. This is good, because C++ programs run as fast as possible, and this is bad, because sometimes we may spend a long time debugging some silly mistake. We would want that the compiler can find such mistakes automatically. And many compilers can! In this post I will show various GCC options that do this. Previously [user:zakharvoit,2015-01-02] already wrote about this [here](/blog/entry/13875). All options that will follow should be added to the GCC command line. In various IDEs you can do it in IDE or compiler settings. Many of the options can also be used with Clang (for example, in Xcode). For MSVC++, I think, there is nothing better than Debug mode and `/W4`. [cut]   GCC warnings ------------------ Of course, the first step to debugging is to enable compi...
Catching silly mistakes with GCC, Ловим глупые ошибки вместе с GCC, can read more about GCC warnings here: https://gcc.gnu.org/onlinedocs/gcc /Warning-Options.html, посте я расскажу о различных параметрах GCC, которые это делают. Эту тему ранее уже освещал, предупреждениях GCC можно прочитать здесь: https://gcc.gnu.org/onlinedocs/gcc /Warning-Options.html, **UPD3**: Added `-Wshift-overflow=2` and `-Wduplicated-cond` (GCC 6+)., **UPD3**: Добавлены `-Wshift-overflow=2` и `-Wduplicated-cond` (GCC 6+)., - Added `-fno-sanitize-recover` (GCC 5+) - Removed `-lmcheck` (replaced by `-fsanitize=address, - `-Wduplicated-cond` — warns about repeated conditions in `if (…) else if (…)` (GCC 6+)., - `-Wduplicated-cond` — предупреждает, если условие в `if (…) else if (…)` повторяется (GCC 6+)., - `-Wlogical-op` — warns about logical operators in places where GCC expects bitwise operators., - `-Wlogical-op` — предупреждает о подозрительном использовании логических операторов там, гдеGCC, - `-Wshift-overflow=2` — warns about left shift overflows (GCC 6+)., - `-Wshift-overflow=2` — предупреждает о переполнении при операциях левого сдвига (GCC 6+)., - `-fsanitize=address` (only in GCC 4.8+ and Clang) — this option inserts memory access checks into, - `-fsanitize=address` (только в GCC 4.8+ и Clang) — этот параметр встраивает в программу проверки, - `-fsanitize=undefined -fno-sanitize-recover` (only in GCC 4.9+ and Clang) — a similar option that, - `-fsanitize=undefined -fno-sanitize-recover` (только в GCC 4.9+ и Clang) — похожий параметр, - Добавлен `-fno-sanitize-recover` (GCC 5+) - Удалён `-lmcheck` (его заменяет `-fsanitize=address, All options that will follow should be added to the GCC command line. In various IDEs you can do it, All this (or selected parts) can be added to GCC command line on the local computer. Therefore, we, GCC options that do this. Previously [user:zakharvoit,2015-01-02] already wrote about this [here, GCC tools ------------------, GCC warnings ------------------, The GCC compiler also contains tools that help find mistakes in programs., These two options are described in https://gcc.gnu.org/onlinedocs/gcc /Debugging-Options.html. There, Все параметры, которые здесь будут приведены, надо добавлять к командной строке GCC. В различных, Инструменты GCC ------------------, Предупреждения GCC ------------------, Сам компилятор GCC тоже содержит инструменты, которые помогают находить ошибки в программах., Эти два параметра описаны в https://gcc.gnu.org/onlinedocs/gcc /Debugging-Options.html. Есть ещё, Это всё (или по выбору) можно добавить к командной строке GCC на своём компьютере. Получается, что

Full text and comments »

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

5.
By neal, 8 years ago, In English
Blowing up unordered_map, and how to stop getting hacked on it C++ has always had the convenient data structures `std::set` and `std::map`, which are tree data structures whose operations take $O(\log n)$ time. With C++11, we finally received a hash set and hash map in `std::unordered_set` and `std::unordered_map`. Unfortunately, I've seen a lot of people on Codeforces get hacked or fail system tests when using these. In this post I'll explain how it's possible to break these data structures and what you can do in order to continue using your favorite hash maps without worrying about being hacked [cut] . So how are they hackable? We always assume hash maps are $O(1)$ per operation (insert, erase, access, etc.). But this depends on a key assumption, which is that each item _only runs into $O(1)$ collisions on average_. If our input data is completely random, this is a reasonable assumption. But this is no longer a safe bet when the input isn't random, especially so if someone is adversarially designing inputs to our code (a.k.a. hacking ph...
. For this we can dig into gcc's implementation on GitHub: https://github.com/ gcc-mirror/gcc. After, ://github.com/gcc-mirror/gcc /blob/5bea0e90e58d971cf3e67f784a116d81a20b927a/libstdc%2B%2B-v3/src/c%2B%2B11, ://github.com/gcc-mirror/gcc., After some searching around we run into [unordered_map.h](https://github.com/gcc -mirror/gcc/blob, The one include on this file leads us to [hashtable-aux.cc](https://github.com/ gcc-mirror/gcc/blob, gcc 6 or earlier, 126271 does the job, and for gcc 7 or later, 107897 will work. Run the code below in

Full text and comments »

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

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...
on Codeforces _without_ using `#pragma GCC target("avx2")`; - It's easier to apply intrinsics to, /onlinedocs/gcc/Vector-Extensions.html)_, 1. [GNU vector extensions](https://gcc.gnu.org/onlinedocs/gcc /Vector-Extensions.html). As always

Full text and comments »

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

7.
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...
[Bugged] Dynamic Bitsets in GCC, ```cpp #include I wonder if it's possible to get GCC to, that GCC also has one? Turns out it's included in the tr2 folder. You can simply include the `, ). You can view the source [here](https://github.com/gcc-mirror/gcc /blob/master/libstdc%2B%2B-v3, GCC also has one? Turns out it's included in the tr2 folder. You can simply include the `

Full text and comments »

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

8.
By MikeMirzayanov, history, 10 years ago, translation, In English
Codeforces: С++14 is supported I am glad to inform you that C++14 has been added to the list of supported languages ​​on Codeforces. The choice fell on the compiler MinGW-w64, version of GCC 6.2.0 (will be updated on new releases). If you have Windows, you can easlily install it using <a href="http://pbox.me">PBOX</a> with one command `pbox install mingw-w64`. Besides trendy features of C++14 (not sure there's a lot to the contests), there are some advantages: * this compiler is faster than mingw-tdm 5.1.0 on cin/cout &mdash; for example, reverse a sequence of $10^6$ integers from 1 to $10^6$ runs 1.5 seconds instead of 2.5 (0.3 vs. 1 if you use `std :: ios :: sync_with_stdio (false)`) * works correctly to print a double with the both specifiers %f and %lf (you should read using %lf) * works correctly to read-write long double with the specifier %Lf * works correctly to read-write long long both with %lld and %I64d It seems that lately we remove support of MinGW C++/C++11 (especially since it is diffic...
Codeforces. The choice fell on the compiler MinGW-w64, version of GCC 6.2.0 (will be updated on new releases, upgrade them to GCC 6 due to backward compatibility issues). Of course, after a while C++14 will appear, пал на MinGW-w64, версия GCC 6.2.0 (будем обновлять по мере выхода). Если у вас Windows, то, ++ и MinGW С++11 будут исключены, тем более что их сложно обновить до GCC 6 из-за сложностей с

Full text and comments »

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

9.
By ToxicPie9, 3 years ago, In English
You won't believe how this simple trick defeated the unexplained bug destroying every top LGM ### TL;DR Currently people are discussing a slowdown bug on Codeforces that seems to happen randomly, and can cause code to run 100x slower and get TLE. More details in [user:pajenegod,2024-03-03]'s [blog post](https://codeforces.me/blog/entry/126654). In this article, I present a mitigation: add the following to your code. ~~~~ #include <windows.h> void *operator new(size_t size) { if (void *ptr = HeapAlloc(GetProcessHeap(), 0, size ? size : 1)) return ptr; throw std::bad_alloc{}; } void operator delete(void *ptr) { HeapFree(GetProcessHeap(), 0, ptr); } ~~~~ <spoiler summary="If you use malloc/free in C++ (you shouldn't), also change them."> ~~~~ void *my_malloc(size_t size) { if (void *ptr = HeapAlloc(GetProcessHeap(), 0, size ? size : 1)) return ptr; throw std::bad_alloc{}; } void my_free(void *ptr) { HeapFree(GetProcessHeap(), 0, ptr); } ~~~~ </spoiler> <spoiler summary="If you use aligned new/delete in C++, also change the...
By default `new` and `delete` with GCC simply call the `malloc` and `free` functions from the C

Full text and comments »

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

10.
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 #pragma GCC optimize("O3") #pragma GCC target("avx2")

Full text and comments »

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

11.
By ToxicPie9, 23 months ago, In English
It's almost 2025, why are you still choosing GCC 7 (32-bit)? This is my answer to https://codeforces.me/blog/entry/137484, in which [user:-is-this-fft-,2024-12-20] asked a bizarre question. This answer is too big for a comment so I made a blog post instead. ## The question The submission [submission:297353626] behaves normally with 180 MiB memory usage while [submission:297352244] got a runtime error due to stack overflow (with 256 MiB stack). Both submissions have identical code, don't seem to contain bugs, and an assertion exists to make sure the recursion is at most $2\times10^5$ layers deep. What's happening? ## TL;DR Notice that the solution with stack overflow uses GCC 7 (32-bit) while the accepted ones use GCC 13 (64-bit). This is not a coincidence. The main reason of unreasonable stack usage boils down to two points: GCC 7, and 32-bit. ## 32-bit First of all, the code is compiled and run in 32-bit mode. Compiling the submission with GCC 7.5 in 32-bit on [godbolt](https://godbolt.org/z/WT9WsdeW4) shows that the `lo...
It's almost 2025, why are you still choosing GCC 7 (32-bit)?, its surrounding code requires stack space to operate, and it seems that the olderGCC 7 is less, solution with stack overflow uses GCC 7 (32-bit) while the accepted ones use GCC 13 (64-bit). This, ## GCC, ., but in this case, GCC actually made the problem a lot worse., First of all, the code is compiled and run in 32-bit mode. Compiling the submission withGCC 7.5, GCC 14 does the optimizing job a lot better. In 32-bit mode, a lot of code is inlined too, but, It's almost 2025, consider using something newer than GCC 7 (32-bit) on Codeforces. Also to the, Notice that the solution with stack overflow uses GCC 7 (32-bit) while the accepted ones useGCC 13, The main reason of unreasonable stack usage boils down to two points: GCC 7, and 32-bit.

Full text and comments »

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

12.
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...
** - Putting `#pragma GCC target("avx2")` **after** some other include, in particular `bits, 1. nor. [“GCC Optimization Pragmas”](https://nor-blog.pages.dev/posts/2021-10-26-gcc-optimization, : ```cpp #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx2") ``` And they're, It is a [known bug](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109753) in GCC 13 and 14. It has, ```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 ```

Full text and comments »

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

13.
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 ...
If you are using Windows, you might first need to install a C++ compiler. A version ofGCC is

Full text and comments »

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

14.
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...
assert in GCC 16, submissions. Because of this, I have reverted the compiler back to GCC 15.2.0 for now., . Although GCC 16 was only released a few months ago and probably will not affect most contests, As you might have heard, in the newest version of GCC, `` is no longer included by `

Full text and comments »

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

15.
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...
`#pragma GCC target("avx512vl")` at the start), #pragma GCC target("avx2"), ~~~~~ #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") ~~~~~

Full text and comments »

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

16.
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...
://www.geeksforgeeks.org/builtin-functions-gcc-compiler/). Now, try to solve these two simple tasks in $O(1)$, then

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

19.
By AliShahali1382, history, 6 years ago, In English
Codeforces Round #722 Editorial Hi, Codeforces! [problem:1529A] problem idea and solution: [user:AmShZ,2021-05-24] <spoiler summary="editorial"> [tutorial:1529A] </spoiler> <spoiler summary="official solution"> ~~~~~ // khodaya khodet komak kon # include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair <int, int> pii; typedef pair <pii, int> ppi; typedef pair <int, pii> pip; typedef pair <pii, pii> ppp; typedef pair <ll, ll> pll; # define A first # define B second # define endl '\n' # define sep ' ' # define all(x)...
~~~~~ #include #pragma GCC optimize ("O2, ~~~~~ #include #pragma GCC optimize ("O2,unroll-loops") //#pragma GCC optimize

Full text and comments »

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

20.
By dacin21, history, 8 years ago, In English
On the mathematics behind rolling hashes and anti-hash tests This blog assumes the reader is familiar with the basic concept of rolling hashes. There are some math-heavy parts, but one can get most of the ideas without understanding every detail. The main focus of this blog is on how to choose the rolling-hash parameters to avoid getting hacked and on how to hack codes with poorly chosen parameters. # Designing hard-to-hack rolling hashes ## Recap on rolling hashes and collisions Recall that a rolling hash has two parameters $(p, a)$ where $p$ is the modulo and $0 \leq a < p$ the base. (We'll see that $p$ should be a big prime and $a$ larger than the size $\left|\Sigma\right|$ of the alphabet.) The hash value of a string $S = s_0 \dots s_{n-1}$ is given by $$ h(S) := \left(\sum\limits_{i=0}^{n-1} a^{n-1-i} s_i\right) \mod p $$ For now, lets consider the simple problem of: given two strings $S, T$ of equal length, decide whether they're equal by comparing their hash values $h(S), h(T)$. Our algorithm declares $S$ and $T$ t...
~~~~~ // pragma version #pragma GCC target ("rdrnd") uint32_t rdrand32

Full text and comments »

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

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

Full text and comments »

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

22.
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...
This is for GCC, clang has an equivalent, if you're on MSVC or something then it's a you problem, ```cpp #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #include "testlib.h

Full text and comments »

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

23.
By Nezzar, history, 6 years ago, In English
Editorial of Codeforces Round #698 (Div.1, Div.2) Thanks for joining us today! Here is the editorial for today's problems: [problem:1478A] <spoiler summary="Tutorial"> [tutorial:1478A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; #define rep(i,n) for (int i=0;i<(int)(n);++i) #define rep1(i,n) for (int i=1;i<=(int)(n);++i) #define range(x) begin(x), end(x) #define sz(x) (int)(x).size() #define pb push_back #define F first #define S second typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int> pii; typedef vector<int> vi; const int maxn=200007; int t,n; int cnt[maxn]; int main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin>>t; while (t--){ cin>>n; rep1(i,n) cnt[i]=0; rep1(i,n){ int u; cin>>u; cnt[u]++; } int mx=0; rep1(i,n) mx=max(mx,cnt[i]); cout<<mx<<"\n"; } ...
~~~~~ //#pragma GCC optimize("Ofast") //#pragma GCC target("sse

Full text and comments »

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

24.
By -is-this-fft-, history, 11 months ago, In English
Fun fact about sync_with_stdio Consider this code: ``` #include <iostream> using namespace std; int main () { ios::sync_with_stdio(false); ios::sync_with_stdio(true); } ``` In GCC, are the C++ streams like `std::cout` etc then synchronized with the corresponding C methods like `printf`? <spoiler summary="Answer"> No &mdash; the second `sync_with_stdio` has no effect at all. There is no trick here: the booleans aren't being interpreted as pointers or anything like that. There is simply no code to handle turning synchronization back on. <spoiler summary="Implementation of sync_with_stdio"> ``` bool ios_base::sync_with_stdio(bool __sync) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 49. Underspecification of ios_base::sync_with_stdio bool __ret = ios_base::Init::_S_synced_with_stdio; // Turn off sync with C FILE* for cin, cout, cerr, clog iff // currently synchronized. if (!__sync && __ret) { // Make sure the standard streams are constructed. i...
In GCC, are the C++ streams like `std::cout` etc then synchronized with the corresponding C methods

Full text and comments »

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

25.
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...
second #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt, #pragma GCC optimize("Ofast")

Full text and comments »

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

26.
By ATSTNG, history, 21 month(s) ago, In English
Undesired -fpermissive behaviour of CF GCC compilers Apparently $24$ hours without sleep and months of coding in scripting languages had the effect on me... During the contest I submitted this [submission:310073998] _Quick challenge: pause reading and find the bug in my solution_ ![ ](/predownloaded/0e/26/0e2631ab99e8f926b267a2b88710962ea2cf0f7e.png) [Link to original art](https://www.artstation.com/artwork/8elamx) When I found out that I failed a div3D on not properly using `int64_t` I was quite surprised, because I double checked that I did it right. I felt very stupid at first, but then I got surprised even more when I figured how exactly this happened. Take a look at the line $25$ ~~~~~ const& r = cr[i]; ~~~~~ It appears that GCC allows to declare variable references omitting type declaration completely when cv-qualifier is present. Yes, without invoking type deduction using `auto`. To be precise expression in form ~~~~~ <cv-qualifier> &<variable-name> = <value>; ~~~~~ appears to be well-formed an...
Undesired -fpermissive behaviour of CF GCC compilers, `-fpermissive` behaviour of GCC. But still, all versions of GCC that I checked in GodBolt will produce, 1. How do I configure GCC locally to produce compile errors on such code? 2. How do I make, But what type you will end up using? You might expect GCC to be smart enough to put `auto` for you, It appears that GCC allows to declare variable references omitting type declaration completely when, It appears to be compilable on all $3$ available G++ compilers on CF and on my localGCC `11.2.0, ]; ~~~~~ It appears that GCC allows to declare variable references omitting type declaration completely when, printf("GCC %d.%d.%d\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); printf("r1 = %d\n, ~~~~~ GCC 11.2.0 r1 = -727379967 r2 = 42 r3 = 42 ~~~~~

Full text and comments »

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

27.
By maomao90, history, 5 months ago, In English
Why is std::deque, std::stack, and std::queue slow and memory inefficient? ## Sidetrack It has been two years since I wrote an educational blog. I've been inactive in the CP community recently as I've shifted my focus to internships. Recently, I observed some interesting behaviour with `std::queue` while profiling an application during my internship, which led me to writing this blog. Most of the images below are taken from the C++ standard https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4950.pdf ## Queues and stacks Queues and stacks do not actually provide any new implementations... They are just wrappers around a container (which is `std::deque`) by default. ![C++ standard std::queue 1](https://codeforces.me/predownloaded/3d/63/3d63990fec1b19722e82b6e01b85679b548b831f.png) ![C++ standard std::queue 2](https://codeforces.me/predownloaded/f4/b3/f4b315a2b12be6525865df61b31aa71bc1b8bbd6.png) ![C++ standard std::stack 1](https://codeforces.me/predownloaded/c0/64/c06407b9c38d964cf8444bb75ed33853e9ffd20b.png) ![C++ standard st...
## <> Detailed GCC Analysis, Below is a brief implementation of deque. (You may refer to the section [below](#gcc-analysis) for, Essentially, the deque stores an array of tiny blocks. In GCC, each tiny block is $512$ bytes, but

Full text and comments »

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

28.
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...
**Note**: You might want to do `#pragma GCC target("bmi2,popcount")` for this to work properly.

Full text and comments »

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

29.
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...
, `#define unsigned unsigned long` would work. Unfortunately, the GCC programmers never thought of such a, And as it turns out, [GCC bitset](https://github.com/gcc-mirror/gcc /blob/master/libstdc%2B%2B-v3

Full text and comments »

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

30.
By errorgorn, 5 years ago, In English
Pragma Insanity: Weird Behaviour with Pragma O3 Here is a simple problem. Count the number of array $A$ of non-negative integers size $N$ such that $\sum\limits_{i=1}^{N} A_i \cdot i=K$. Where $N,K \leq 5000$. Find the answer modulo $1000000007$. I unfortunately cannot share the link to a submissions page as it is on a private local judge. Update: I have asked judge devs of the local judge, the compile command is `g++ -O2 -o {compiledName} {sourceName} -m64 -static -std=gnu++14 -lm -s -w -Wall -Wshadow -fmax-errors=512` But anyways, here is the problem. <spoiler summary="AC code"> ~~~~~ #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #include <bits/stdc++.h> using namespace std; #define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--)) const int MOD=1000000007; int n,k; int memo[5005]; int main(){ cin>>n>>k; memo[k]=1; rep(x,n+1,1) if (k>=x) rep(y,k+1,x){ assert(y-x>=0); memo[y-x]=(memo[y-x]+...
$729287017$, but the WA code gives $735199643$ (testing on atcoder custom invocation with C++ (GCC 9.2.1, #pragma GCC optimize("O3"), , here is the problem. ~~~~~ #pragma GCC optimize("O3,unroll-loops, Below is another set of AC and WA codes where the only difference is `#pragma GCC optimize("O3")`., ~~~~~ #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

Full text and comments »

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

31.
By ExplodingFreeze, 5 years ago, In English
Codeforces Round #754 (Div. 2) Editorial Thank you for participating! We hope you enjoyed the contest. [problem:1605A] Authored and prepared by [user:JeevanJyot,2021-11-12] <spoiler summary="Hint 1"> What happens to the value of $d(a_1, a_2, a_3)$ if you perform an operation on $a_1$ and $a_3$? </spoiler> <spoiler summary="Hint 2"> What happens if you perform an operation on $a_1$ and $a_2$? </spoiler> <spoiler summary="Hint 3"> Can we use negative values to improve the worst answer? </spoiler> <spoiler summary="Solution"> [tutorial:1605A] </spoiler> <spoiler summary="Solution [c++] (JeevanJyot)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int T; cin >> T; while(T--) { int a, b, c; cin >> a >> b >> c; cout << ((a + c - 2 * b) % 3 == 0 ? 0 : 1) << "\n"; } return 0; } ~~~~~ </spoiler> <spoiler summary="Solution [Kotlin] (ExplodingFreeze...
> #include #include #pragma GCC target ("avx2

Full text and comments »

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

32.
By djm03178, 2 years ago, In English
Blowing up unordered_map 2024 edition It is already well-known that using `unordered` series in Codeforces is super dangerous, and it is not recommended to use them at all unless you know how to prevent them properly (well, even if you know, just using a regular `map` or `set` is more beneficial in most cases). Thanks to [Blowing up unordered_map, and how to stop getting hacked on it](https://codeforces.me/blog/entry/62393), it is easy to access to the basics of hacking these hash-based structures. In this blog, I'm going to get into more details on how it works, and the ideas to hack them with various constraints on the variables. The basics ------------------ As mentioned in the linked blog, gcc implements its hash table simply by modding the key with certain primes, and these primes vary between different versions of gcc. So, basically the easiest way to make a hack case is to put numerous distinct multiples of these primes. However, an important thing to note is that it's a _list_ of primes instead of just one pr...
size in [this list](https://github.com/gcc-mirror/gcc /blob/5bea0e90e58d971cf3e67f784a116d81a20b927a, The basics ------------------ As mentioned in the linked blog, gcc implements its hash table

Full text and comments »

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

33.
By peltorator, 5 years ago, In English
Top 10 best Codeforces blog posts of 2021 (in my humble opinion) I really like good blog posts. And that's the main reason I like Codeforces. But as we all know, it's hard to find good blog posts here. So let's help each other and share our favorite posts, which were uploaded to Codeforces in the last year! I will share my top 10, and I encourage you to share some of your favorites in the comments. #### 10. [Heuristic algorithm for Hamiltonian path in directed graphs](https://codeforces.me/blog/entry/90513) by [user:Miracle03,2021-12-24] An absolutely incredible algorithm which kinda sometimes solves the Hamiltonian path problem on some random and special kind of graphs. #### 9. [I compiled a list of almost all useful blogs ever published on Codeforces](https://codeforces.me/blog/entry/91363) by [user:parveen1981,2021-12-24] This blog has a purpose that's similar to the purpose of the blog you're reading right now. A great source of interesting blog posts! #### 8. [Fast modular multiplication](https://codeforces.me/blog/entry/96759...
#### 3. [[Tutorial] GCC Optimization Pragmas](https://codeforces.me/blog/entry/96344) by [user:nor

Full text and comments »

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

34.
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 #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

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...
In other words, `#pragma GCC target("avx2,tune=native")` tends to be _really_ useful in linear

Full text and comments »

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

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

Full text and comments »

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

37.
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...
#pragma GCC unroll max_logn for (size_t z = 0; z < max_logn; z, - **Autovectorization is enabled**: Use `#pragma GCC` with `optimize("O3")` and `target("avx2

Full text and comments »

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

38.
By Keshi, 5 years ago, In English
Codeforces Global Round 17 Editorial ###[problem:1610A] Idea: [user:Anti-Light,2021-11-24], Preparation: [user:DeadlyCritic,2021-11-24] <spoiler summary="Hints"> <spoiler summary="Hint 1"> $ans \le 2$ </spoiler> <spoiler summary="Hint 2"> If $n = 1$ and $m = 1$ then $ans = 0$. <a href="https://emoji.gg/emoji/5500-thosewhoknow"><img src="https://emoji.gg/assets/emoji/5500-thosewhoknow.png" width="20px" height="20px" alt="ThoseWhoKnow"></a> </spoiler> </spoiler> <spoiler summary="Solution"> [tutorial:1610A] </spoiler> <spoiler summary="Implementation"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(); cout.tie(); int t; cin >> t; while(t--){ int n, m; cin >> n >> m; if(n == 1 && m == 1){ cout << "0\n"; } else if(min(n, m) == 1){ cout << "1\n"; } else cout << "2\n"; } } ~~~~~ </spoiler> ###[p...
~~~~~ #include #pragma GCC optimize ("O2

Full text and comments »

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

39.
By pajenegod, history, 7 years ago, In English
Explanation to weird/strange floating point behaviour in C++ # Introduction I'm writing this blog because of the large number of blogs asking about why they get strange floating arithmetic behaviour in C++. For example: "WA using GNU C++17 (64) and AC using GNU C++17" https://codeforces.me/blog/entry/78094 "The curious case of the pow function" https://codeforces.me/blog/entry/21844 "Why does this happen?" https://codeforces.me/blog/entry/51884 "Why can this code work strangely?" https://codeforces.me/blog/entry/18005 and many many more. # Example Here is a simple example of the kind of weird behaviour I'm talking about <spoiler summary="Example showing the issue"> ~~~ #include <iostream> using namespace std; double f(double a, double b) { return a * a - b; } int main() { cout.precision(60); // Calculate 10*10 - 1e-15 double ans; ans = f(atof("10"), atof("1e-15")); cout << (double) ans << '\n'; cout << (int) ans << "\n\n"; ans = f(atof("10"), atof("1e-15...
(version 2 or later), which supports both float and double arithmetic. On GCC you can turn this on with the, ~~~~~ // #pragma GCC target("fpmath=sse,sse2") // Turns off excess precision // #pragmaGCC

Full text and comments »

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

40.
By E869120, 8 years ago, In English
[Fixed] Speeding Up for Naive Algorithm Hello Codeforces!<br /> <br /> Recently, in JOI 2018 Spring Camp, a young genius [QCFium](https://atcoder.jp/users/QCFium), wrote a naive $O(NQ)$ algorithm in the problem [Examination](https://www.ioi-jp.org/camp/2019/2019-sp-tasks/day1/examination-en.pdf), and got the perfect score. The code is as follows <font color="red">(Fixed on 2025/5/26)</font>:<br /> <br /> <code>#pragma GCC target("avx2")</code><br /> <code>#pragma GCC optimize("O3")</code><br /> <code>#pragma GCC optimize("unroll-loops")</code><br /> <code>//Naive Solution as follows...</code><br /> <br /> I thought that it was very surprising, but actually, even $N,Q \leq 100,000$, with the only 3 lines $O(NQ)$ naive algorithm actually got accepted. To check whether this speedup is actually effective or not, I wrote these two codes: one is with the 3-line speedup, and the other is without the 3-line speedup.<br /> <br /> <spoiler summary="Code A (With speedup)"> ~~~~~ #include <iostream> using namespace std; ...
as follows (Fixed on 2025/5/26): #pragma GCC target, #pragma GCC target("avx2") #pragma GCC optimize("O3") , ; #pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops")

Full text and comments »

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

41.
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):...
// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") // #pragma GCC optimize("O3") // #pragmaGCC

Full text and comments »

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

42.
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 #pragma GCC optimize("O3,unroll-loops")

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

45.
By AkiLotus, 7 years ago, In English
Codeforces Round #614 Editorial All themes written by [user:Akikaze,2020-01-13] (I am the only one in the team playing Cytus II anyway :D). [problem:1293A] ------------------ Author: [user:xuanquang1999,2020-01-13] Development: [user:xuanquang1999,2020-01-13], [user:Akikaze,2020-01-13] Editorialist: [user:xuanquang1999,2020-01-13], [user:Akikaze,2020-01-13] <spoiler summary="Tutorial"> [tutorial:1293A] </spoiler> <spoiler summary="Solution (Akikaze, C++)"> Submission link: [submission:69149995] <spoiler summary="Source code in plain text"> ~~~~~ #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' int n, s, k; vector<int> a; void Input() { cin >> n >> s >> k; a.clear(); a.resize(k); for (auto &z: a) cin >> z; } void Solve() { for (int i=0; i<=k; i++) { if (s-i >= 1 && find(a.begin(), a.end(), s-i) == a.end()) {cout << i << endl; return;} if (s+i <= n && find(a.begin(), a.end(), s+i) == a.end()) {cout << i << endl;...
~~~~~ #pragma GCC optimize("Ofast")

Full text and comments »

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

46.
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" #pragma GCC optimize

Full text and comments »

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

47.
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...
`. - `insert_range`/`append_range`/`prepend_range`/`assign_range` for containers (not inGCC yet). - `print

Full text and comments »

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

48.
By kevlu8, 2 years ago, In English
GCC Optimization Pragmas Lie to You GCC has many optimization pragmas that can be prepended to files. Generally, they *should* speed up your code the same amount as the equivalent command-line argument, however this is not always the case. Theoretically, you would expect ```cpp #pragma GCC optimize("O3") ``` to optimize your code the same way as ```sh g++ main.cpp -O3 ``` But it doesn't! Let's take a look at an example program: ```cpp #pragma GCC optimize("O3") #include <bits/stdc++.h> using namespace std; #define SZ 10000005 int arr[SZ] = {}; int main() { iota(arr, arr+SZ, 1); int tgt = 19999473; unordered_set<int> s(arr, arr+SZ); for (int i = 0; i < SZ; i++) { if (s.count(tgt-arr[i])) { cout << arr[i] << ' ' << tgt-arr[i] << '\n'; break; } } } ``` This is a pretty simple and well-known solution to a problem. It solves the Two-Sum problem using a hashset. Here's a chart showing the runtime of the program with a...
GCC Optimization Pragmas Lie to You, GCC has many optimization pragmas that can be prepended to files. Generally, they *should* speed up, Most of the time, there is no reason to use `#pragma GCC optimize("O3")` over `-O3`, because you, ```cpp #pragma GCC optimize("O3") #include using namespace std;, ```cpp #pragma GCC optimize("O3") ```, ```cpp #pragma GCC optimize("O3") static int return5() { return 5; } int main

Full text and comments »

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

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

Full text and comments »

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

50.
By DNR, 2 years ago, In English
Dynamic Bitset Implementation #### Disclaimer: It might have bugs, don't send me death threats if you FST. I couldn't find a nice dynamic bitset template so I wrote one. It can be found [here](https://github.com/welcome-to-the-sunny-side/libra/blob/main/data/bitset.cpp). It has additional functionality as compared to `std::bitset` (you can answer many kinds of range queries on it, for example: "Find $k$-th set bit in range $[l, r]$). <spoiler summary="Some poor documentation"> #### General - It is used to store a 0-indexed boolean array. - Just like regular bitset, index 0 is the rightmost (sense of direction is important for `>>` and `<<`). - It uses $\lceil n/B \rceil$ blocks of size $B$ (which should be equal to bitwidth of $T$) to represent a boolean array of length $n$. Note that there may be some unused bits at the end of the last block. We will always have these unused bits set to 0. #### Functions For most functions, their use is obvious. For others: <spoiler summary="hel...
``` #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2

Full text and comments »

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

51.
By AkiLotus, 7 years ago, In English
Ozon Tech Challenge 2020 Editorial We apologize for the huge gap from F to G. In the meantime, you can join the Discord server of AC &mdash; a competitive programming forum &mdash; [here](https://discord.gg/YgaRNT). [problem:1305A] ------------------ Author: [user:Ari,2020-03-03] Development: [user:Ari,2020-03-03], [user:dorijanlendvaj,2020-03-03] Editorialist: [user:Ari,2020-03-03] <spoiler summary="Tutorial"> [tutorial:1305A] </spoiler> <spoiler summary="Solution (Ari, C++)"> Submission link: [submission:72363754] <spoiler summary="Source code in plain text"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; vector<int> a(n), b(n); for(int i = 0; i < n; i++) { cin >> a[i]; } for(int i = 0; i < n; i++) { cin >> b[i]; } if(a == vector<int>({1, 8, 5}) && b == vector<int>({8, 4, 5})) { cout << "1 8 5\...
~~~~~ #pragma GCC optimize("Ofast")

Full text and comments »

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

52.
By orz, history, 3 years ago, In English
C++20 is back In contests and in the custom invocation, after a pause, one can again find GNU G++20 64-bit. However, the [slowdown issue](https://codeforces.me/blog/entry/126654) because of which the language disappeared persists, there are still snippets of code that can slow down the execution on Codeforces servers by a factor of 100 or so. So what is the official position of Codeforces headquarters and of our community on that? 1. Are there general methods of constructing testcases that can exploit this GCC/Windows bug and therefore slow down solutions (like there are [anti-hash tests](https://codeforces.me/blog/entry/62393) for solutions using `unordered_set`)? Are there methods that slow down both contest mode and custom invocation mode (since [submission:249807302] is only slow in the contest mode whereas [submission:253289473] is only slow in the custom invocation)? 2. If so, should we expect such tests in future contests, will such methods be used during the test preparation in co...
1. Are there general methods of constructing testcases that can exploit this GCC /Windows bug and

Full text and comments »

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

53.
By Vladosiya, history, 5 years ago, translation, In English
Codeforces Round #776 (Div. 3) Editorial [problem:1650A] Idea: [user:MikeMirzayanov,2022-03-09] <spoiler summary="Tutorial"> [tutorial:1650A] </spoiler> <spoiler summary="Solution"> ~~~~~ #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) { string s, t; cin >> s >> t; bool yes = false; forn(i, s.length()) if (s[i] == t[0] && i % 2 == 0) yes = true; cout << (yes ? "YES" : "NO") << endl; } } ~~~~~ </spoiler> [problem:1650B] Idea: [user:Vladosiya,2022-03-09] <spoiler summary="Tutorial"> [tutorial:1650B] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> //#define int long long #define mp make_pair #define x first #define y second #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() #pragma GCC optimize("Ofast") #pragma GCC optimize("no-stack-protector...
#pragma GCC optimize("Ofast") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize

Full text and comments »

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

54.
By rabaiBomkarBittalBang, 5 years ago, In English
Codeforces Round #724 — Editorial We hope you liked the problems! If you’re curious about the two different problem formats, initially [user:Tlatoani,2021-06-06], [user:golions,2021-06-06], [user:qlf9,2021-06-06] and I were working on Omkar 3 with [user:antontrygubO_o,2021-06-06] while [user:hu_tao,2021-06-06] was working on a separate round with [user:isaf27,2021-06-06]. We eventually decided to join forces and combine the rounds, resulting in the current Omkar 3. <h1>[problem:1536A]</h1> Idea: [user:rabaiBomkarBittalBang,2021-06-06] Preparation: [user:rabaiBomkarBittalBang,2021-06-06], [user:Tlatoani,2021-06-06], [user:qlf9,2021-06-06] [Video editorial](https://www.youtube.com/watch?v=GZeihS2xTSc) <spoiler summary="Hint"> Consider what happens when $a$ contains a negative number. </spoiler> <spoiler summary="Solution"> We first claim that if any negative number exists in $a$, then no solution exists. Denote $p$ as the smallest number in $a$ and $q$ as another arbitrary number in the array (as $n...
#endif #pragma GCC optimize("O3") #include

Full text and comments »

55.
By shishyando, 5 years ago, In English
Codeforces Round #781 (Div. 2) Editorial Again, I hope that you liked all the problems. Share your ideas and solutions in the comments, because there are always different ones! So, the editorial: <spoiler summary="A: GCD vs LCM"> [problem:1665A] <spoiler summary="Editorial"> In this problem it is enough to print $n - 3$, $1$, $1$, $1$. It is easy to see that this answer is correct for any $n \ge 4$. </spoiler> <spoiler summary="Implementation (C++, shishyando)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T --> 0) { int n; cin >> n; cout << n - 3 << ' ' << 1 << ' ' << 1 << ' ' << 1 << '\n'; } return 0; } ~~~~~ </spoiler> </spoiler> <spoiler summary="B: Array Cloning Technique"> [problem:1665B] <spoiler summary="Editorial"> We will use a greedy technique. Let's find the most common element in the array. Let it be $x$ and let it occur $k$ times in the array. Then let's make a copy where all elements...
~~~~~ #pragma GCC

Full text and comments »

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

56.
By dreamoon_love_AA, history, 7 years ago, In English
Codeforces Round #631 Editorial [tutorial:1330A] <spoiler summary="author's code:"> ~~~~~ #include<cstdio> const int MAX_V = 201; bool achieve[MAX_V]; void solve() { int n, x; scanf("%d%d", &n, &x); for(int i = 1; i <= n + x; i++) { achieve[i] = false; } for(int i = 1; i <= n; i++) { int ranking; scanf("%d", &ranking); achieve[ranking] = true; } for(int k = n + x; k > 0; k--) { int v = 0; for(int i = 1; i <= k; i++) { if(!achieve[i]) v++; } if(v <= x) { printf("%d\n", k); return; } } } int main() { int T; scanf("%d", &T); while(T--) solve(); return 0; } ~~~~~ </spoiler> [tutorial:1330B] <spoiler summary="author's code"> ~~~~~ #include<cstdio> const int SIZE = 200000; int p[SIZE]; int ans[SIZE][2]; int ans_cnt; bool judge(int a[], int n){ static int used[SIZE+1]; for(int i = 1; i <= n; i++) used[i] = 0...
~~~~~ //#pragma GCC, ~~~~~ //#pragma GCC optimize("O3") #include

Full text and comments »

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

57.
By ooaa, history, 3 years ago, translation, In English
Codeforces Round #922 (Div. 2) Разбор Всем привет! Надеемся, что вам понравились наши задачи! Спасибо за участие! [1918A &mdash; Кирпичная стена](https://codeforces.me/contest/1918/problem/A) Автор: [user:ooaa,2024-01-30] <spoiler summary="Разбор"> Устойчивость стены &mdash; это число горизонтальных кирпичей минус число вертикальных. Так как горизонтальный кирпич длины хотя бы $2$, в одном ряду можно разместить не более $\lfloor\frac{m}{2}\rfloor$ горизонтальных кирпичей. Поэтому ответ не превосходит $n \cdot \lfloor\frac{m}{2}\rfloor$. С другой стороны, если размещать в ряду горизонтальные кирпичи длины $2$, и, когда $m$ нечётно, последний кирпич длины $3$, то в каждом ряду будет ровно $\lfloor\frac{m}{2}\rfloor$ горизонтальных кирпичей, и вертикальных кирпичей в стене вообще не будет. Так достигается максимальная устойчивость $n \cdot \lfloor\frac{m}{2}\rfloor$. Решение &mdash; это одна формула, асимптотика $O(1)$. </spoiler> <spoiler summary="Решение"> ~~~~~ #include <bits/stdc++.h> ...
~~~~~ //#pragma GCC optimize("Ofast") //#pragma

Full text and comments »

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

58.
By Vladosiya, history, 4 years ago, translation, In English
Codeforces Round 855 (Div. 3) Editorial [problem:1800A] Idea: [user:Vladosiya,2023-03-03], [user:MikeMirzayanov,2023-03-03] <spoiler summary="Tutorial"> [tutorial:1800A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; string s; cin >> s; transform(s.begin(), s.end(), s.begin(), [] (char c) { return tolower(c); }); s.erase(unique(s.begin(), s.end()), s.end()); cout << (s == "meow" ? "YES" : "NO") << "\n"; } int main(){ int t; cin >> t; while(t--) solve(); } ~~~~~ </spoiler> [problem:1800B] Idea: [user:myav,2023-03-03] <spoiler summary="Tutorial"> [tutorial:1800B] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; const int N = 26; void solve(){ int n, k; cin >> n >> k; string s; cin >> s; vector<int>big(N, 0), small(N, 0); for(auto &i : s){ if('A' <= i && 'Z' >= i) b...
~~~~~ #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops

Full text and comments »

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

59.
By DishonoredRighteous, history, 4 years ago, In English
Codeforces Round #866 (Div.1, Div.2, based on Lipetsk Team Olympiad) Editorial [problem:1820A] Author: [user:FairyWinx,2023-04-16] Preparation: [user:FairyWinx,2023-04-16] <spoiler summary="Editorial"> [tutorial:1820A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; if (s == "^") { cout << 1 << '\n'; continue; } int ans = 0; if (s[0] == '_') ++ans; if (s.back() == '_') ++ans; for (int i = 0; i < (int) s.size() - 1; ++i) { if (s[i] == '_' && s[i + 1] == '_') ++ans; } cout << ans << '\n'; } } ~~~~~ </spoiler> [problem:1820B] Author: [user:golikovnik,2023-04-16] Preparation: [user:teraqqq,2023-04-16] <spoiler summary="Editorial"> [tutorial:1820B] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using nam...
~~~~~ // #pragma comment(linker, "/stack:200000000") // #pragma GCC, ~~~~~ //#pragma GCC target("trapv") #include #include

Full text and comments »

60.
By dmkozyrev, history, 3 years ago, In English
[Tutorial] Quick start in solving problems on GPU + CPU Hello, codeforces! Do you have modern GPU and CPU and want to calculate something with them, but you don't know how to do it? Dont be upset, because you can read this blog and run your first GPU program on your AMD/Intel/NVIDIA GPU. I will describe an installation process and then we will dive into the C++ code. As an example, we will calculate a lot of mazes for [Bug Game](https://codeforces.me/blog/entry/115144) in parallel. For doing this in simple way, we will use library [Boost.Compute](https://www.boost.org/doc/libs/1_80_0/libs/compute/doc/html/index.html), which is a C++ STL-style wrapper over OpenCL library. [cut] ... Installation for MacOS (Apple M1 Pro) ================== As [user:Gosunov,2023-06-10] said, `OpenCL` and `g++` are pre-installed on `MacOS`. Everything that you have to do is install `Boost` with command `brew install boost`. After this you will be able to compile your program with command `g++ -std=c++17 -O3 -I/opt/homebrew/Cellar/boost/1.81.0_1/...

Full text and comments »

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

61.
By MohammadParsaElahimanesh, 4 years ago, In English
Codeforces Global Round 23 Editorial Hi Codeforces, I've tried my best to make a different editorial, I wish you enjoy it ... [problem:1746A] problem author: [user:MohammadParsaElahimanesh,2022-10-15], [user:AmirrzwM,2022-10-15] <spoiler summary="step by step solution"> step 1: It's obvious that the answer is "NO" if $a_{i} = 0$ for all $1 \le i \le n$. step 2: Lets prove that the answer is "YES" if $a_{i} = 1$ for at least one $1 \le i \le n$. step 3: If size of $a$ is equal to $k$, just use second type operation once and we are done. step 4: Otherwise (if $|a| > k$), there will be three cases: (assume that $a_{j} = 1$) - if $j > 2$, you can use first type operation on first and second element and decrease size of $a$ by 1. - else if $j < |a|-1$, you can use first type operation on last and second to last element and decrease size of $a$ by 1. - else, it can be shown easily that $|a| = 3$ and $k = 2$ so you can use second type operation twice and turn $a$ into a single $1$. In ...
~~~~~ /// In the name of God #pragma GCC optimize("Ofast","unroll

Full text and comments »

62.
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 #pragma GCC target("avx2") #pragma GCC optimize("Ofast

Full text and comments »

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

63.
By wuhudsm, history, 16 months ago, In English
TheForces Round #43 (DIV2-Forces) Editorial Reminder: We welcome you to participate in the official DIV1/DIV2 round scheduled on the 31st! [A](https://codeforces.me/gym/106014/problem/A) Idea:[user:tamzid1,2025-07-25] <spoiler summary="solution"> We can see if $x$ is a perfect square, $x^x$, $x^{(x^x)}$, $\ldots$ are also perfect square. Proof: assume $x=y^2$, $x^z=(y^z) \cdot (y^z)$. So the answer is the number of perfect squares not greater than $n$. There are exactly $\lfloor \sqrt{n} \rfloor$ integers $x$ (with $1 \leq x \leq n$) such that $x$ is a mystic number. </spoiler> <spoiler summary="code(C++)"> ```cpp #include <iostream> #include <cmath> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; cout << static_cast<int>(sqrt(n)) << '\n'; } return 0; } ``` </spoiler> <spoiler summary="Rate the Problem"> Amazing problem: Goo...
#pragma GCC optimize("unroll-loops") #pragma gcc optimize("Ofast") #pragma GCC optimization

Full text and comments »

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

64.
By wuhudsm, history, 15 months ago, In English
TheForces Round #44 (DIV3.5-Forces) Editorial [A](https://codeforces.me/gym/106049/problem/A) Idea:[user:Muhammad-Ahmad,2025-08-22] <spoiler summary="solution"> The key observation is that the parity of the distance between Alice and Bob always changes after one move. Therefore, if $|x - y|$ is even, Alice can always move closer to Bob and corner him to win. Otherwise, Bob will win. </spoiler> <spoiler summary="code(C++)"> ```cpp #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <typename T> using oms = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>; #define mod 1000000007 #define mod2 998244353 #define ll long long #define bl __int128_t #define pb push_back #define all(v) v.begin(),v.end() #define bs binary_search #define rall(v) v.rbegin()...
#pragma GCC optimize("unroll-loops") #pragma gcc optimize("Ofast") #pragma GCC optimization

Full text and comments »

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

65.
By ymmparsa, 3 years ago, In English
[Tutorial] A fast and easy way to factorize integers up to 1e9 This blog focuses on the GCC compiler. The most basic way to find a prime factorization for an integer $n$ is to test every possible divisor up to $\sqrt{n}$. This can be optimized by precomputing primes and only testing those. What else can we do? Note that the modulo operation is rather expensive. To optimize it, we can use something like the Montgomery multiplication, but it's too complicated for an "easy way". But also note that when the divisor is a compile-time constant, the compiler optimizes the modulo operation (or division, for that matter) to cheap multiplication and bit-shift operations. Let's take advantage of that: ~~~~~ #include <bits/stdc++.h> using namespace std; typedef uint32_t u32; // The cold attribute tells the compiler that this function is unlikely to be // called. Without it, compilation will take much more time because the // compiler tries to optimize the function calls. Attributes are a GCC // extension. __attribute__((cold)) void factor...
calls. Attributes are a GCC // extension. __attribute__((cold)) void factor_helper(vector &vec, This blog focuses on the GCC compiler.

Full text and comments »

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

66.
By djm03178, 2 years ago, In English
Different behavior between gcd and __gcd I experienced something weird while solving [problem:2050F]. Basically, I tried solving it by decomposing the array into $\mathcal{O}(\sqrt{n})$ blocks. I submitted several of them each using difference size of blocks, and they passed in 2s during the contest. Surprisingly, in system tests, all of my submissions got TLE on my hack test that was used to hack other similar solutions that worked much slower in the original tests. It felt really weird, because the most basic `gcd` implementation we learn is something like this: ~~~~~ int G(int a, int b) { return b ? G(b, a % b) : a; } ~~~~~ Although a single call for this function takes $\mathcal{O(\log{x}})$ time where $x$ is the value of the input, when we repeatedly apply this fuction $k$ times where either $a$ or $b$ is the result of a previous call on this function, it should only take $\mathcal{O}(k+\log{x})$ because the depth of the recursion gets deeper only when the result gets smaller. Thus, my solution should o...
The first one uses `std::gcd`, the second one uses `__gcd` which is a gcc extension, and the third

Full text and comments »

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

67.
By Newtech66, 5 years ago, In English
Codeforces Round #782 (Div. 2) Editorial Thank you everyone for your participation. Do vote under the Feedback section, and feel free to give your review of the problems in the comments. --- [problem:1659A] <br> Idea: [user:TimeWarp101,2022-04-17] <br> Editorial: [user:TimeWarp101,2022-04-17] <spoiler summary="Hints"> <spoiler summary="Hint 1"> Is it a good idea to have consecutive ``B``'s? </spoiler> <spoiler summary="Hint 2"> If you space out all the ``B``'s, how many regions do you have to place the ``R``'s into? </spoiler> <spoiler summary="Hint 3"> What is the best way of placing the ``R``'s into $b+1$ regions such that the maximum number of ``R``'s in a region is minimum? </spoiler> </spoiler> <spoiler summary="Solution"> [tutorial:1659A] </spoiler> <spoiler summary="Implementation (C++)"> ~~~~~ #include<bits/stdc++.h> using namespace std; using lol=long long int; #define endl "\n" int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int _=1; cin>>_; ...
~~~~~ #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("avx

Full text and comments »

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

68.
By Ashwanth.K, history, 2 years ago, In English
Meta Hackercup Practice D2 problem #### Problem D2: Line of Delivery (Part 2) [Link](https://www.facebook.com/codingcompetitions/hacker-cup/2024/practice-round/problems/D2) Hello everyone, I'd like to talk about Problem D2 from the recent Meta Hacker Cup 2024 Practice Round. The solution suggests that we can use a treap data structure to efficiently handle the operations described in the problem. Operation 1) Insert a stone at $E_i^{th}$ empty position. Operation 2) Move all stones to the left of the inserted stone by 1 unit in the negative direction. Yes, treaps can be used to solve this problem, but I’ve come up with a simpler solution using a vector approach. Let's maintain an array called `emptyPlaces` that stores information about all the empty spots. In this array, I track how many balls are located immediately to the right of each empty position. So `emptyPlaces[i]` denoted how many consecutive balls are immediately right towards $i^{th}$ empty ...
``` // #pragma GCC optimize("Ofast") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm

Full text and comments »

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

69.
By AkiLotus, history, 8 years ago, In English
Codeforces Round #554 (Div. 2) Editorial [problem:1152A] ------------------ Author: [user:xuanquang1999,2019-04-24] Development: [user:xuanquang1999,2019-04-24], [user:Akikaze,2019-04-24], [user:GreenGrape,2019-04-24] Theme development: [user:Akikaze,2019-04-24], [user:GreenGrape,2019-04-24] Editorialist: [user:xuanquang1999,2019-04-24] <spoiler summary="Tutorial"> [tutorial:1152A] </spoiler> <spoiler summary="Solution (xuanquang1999)"> Submission link: [submission:53259456] <spoiler summary="Source code in plain text"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main(int argc, char* argv[]) { int n, m; scanf("%d%d", &n, &m); vector<int> a(n), b(m); for(int i = 0; i < n; ++i) scanf("%d", &a[i]); for(int i = 0; i < m; ++i) scanf("%d", &b[i]); int c0 = 0, c1 = 0; for(int i = 0; i < n; ++i) if (a[i]%2 == 0) ++c0; else ++c1; int k0 = 0, k1 = 0; for(int i = 0; i < m; ++i...
") #pragma GCC optimize("Ofast")

Full text and comments »

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

70.
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...
#define se second #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt

Full text and comments »

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

71.
By dmkozyrev, history, 7 years ago, translation, In English
Efficient implementation of Karatsuba multiply with auto-vectorization **In this blog you can found an efficient implementation of Karatsuba multiply of two polinomials, that sometimes can be used instead of FFT** [cut] $$\text{ }$$ Hello everyone! One man ask me to write a code for calculation of $1.000.000$ fibonacci number in C++. This broblem [has been solved](https://ideone.com/qO88bh) in time less than 1 second with Karatsuba multiply. After it, I tried to use this code in standart problems like "we have two strings of letters $\text{ATGC}$ and want to calculate optimal cyclic rotation of one of them so number of equal positions will be greatest" with Karatsuba multiply, and these problems have been successfully solved. There are a lot of naive implementations, but [user:MrDindows,2020-02-24] helped to write a most efficient of all simple implementations. Idea of Karatsuba multiply ================== We have two polinomials $a(x)$ and $b(x)$ with equal length $2n$ and want multiply them. Let suppose that $a(x) = a_0(x) + x^n \cdot a...
``` #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC

Full text and comments »

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

72.
By wuhudsm, history, 2 years ago, In English
Codeforces Round 960 (Div. 2) Editorial Thank you for participation and we hope you enjoy this round :) Additionally, we sincerely invite you to join the unofficial round of TheForces Community tomorrow. Compete alongside many high-rated participants and earn your own rating in a our own rating system([TheForces Rating System](https://theforces.netlify.app/ratings))! For more details, pls read https://codeforces.me/blog/entry/131733. #### [A &mdash; Submission Bait](https://codeforces.me/contest/1990/problem/A) <spoiler summary="hint1"> For Alice, what if choosing the maximum value doesn't work? </spoiler> <spoiler summary="hint2"> Consider parity. </spoiler> <spoiler summary="solution 1"> Case $1$: When all values appear an even number of times, Alice will lose. This is because no matter which number Alice chooses, Bob can mimic Alice's move. Case $2$: When at least one value appears an odd number of times, Alice will win. Alice only needs to choose the maximum value that appears an odd number ...
``` // #pragma GCC optimize("O3,unroll-loops") // #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt

Full text and comments »

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

73.
By AkiLotus, 8 years ago, In English
Codeforces Round #538 (Div. 2) Editorial *Model solutions are now available.* *[user:GreenGrape,2019-02-10] and I will write more about problem F, including an alternative data structures (still quite tight on time limit) ;)* [problem:1114A] ------------------ Author: [user:Akikaze,2019-02-10], [user:GreenGrape,2019-02-10] Development: [user:Akikaze,2019-02-10], [user:GreenGrape,2019-02-10], [user:neko_nyaa,2019-02-10] Editorialist: [user:Akikaze,2019-02-10] <spoiler summary="Tutorial"> First of all, we can see the grape preference is hierarchically inclusive: the grapes' types Andrew enjoys are some of those that Dmitry does, and Dmitry's favorites are included in Michal's. Let's distribute the grapes to satisfy Andrew first, then to Dmitry, then Michal. If any of the following criteria is not satisfied (which means one of our friends is not happy), then we can immediately say that no distributions are available: - Andrew must have at least $a$ green grapes. So we need, $x \le a$. - Dmitry can ha...
~~~~~ #define _CRT_SECURE_NO_WARNINGS #pragma GCC, ") #pragma GCC optimize("Ofast")

Full text and comments »

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

74.
By MarkBcc168, history, 4 years ago, In English
Codeforces Round #807 (Div 2.) Editorial Thanks for participating. We apologize for problem F that has appeared before. Still, we hope you all enjoy our round! [problem:1705A] ---------------- Author: [user:MarkBcc168,2022-07-15] <spoiler summary="Hint 1"> First, sort $h_1 \leq h_2 \leq \dots \leq h_{2n}$. There is a very explicit description to which $h_i$'s work. </spoiler> <spoiler summary="Hint 2"> What is the optimal arrangement that maximizes the minimum difference across all pairs? </spoiler> <spoiler summary="Tutorial"> We have a very explicit description of whether the arrangement is possible. Sort the heights so that $h_1 \leq h_2 \leq \dots \leq h_{2n}$. Then, there exists such arrangement if and only if all the following conditions hold. $$\begin{align*} h_{n+1}-h_1 &\geq x \\ h_{n+2}-h_2 &\geq x \\ &\vdots \\ h_{2n}-h_n &\geq x \end{align*}$$ We present two proofs. ----- *Proof 1 (Direct Proof).* Suppose that the arrangement is possible. We will show that for each $i$, we have...
~~~~~ #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

Full text and comments »

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

75.
By dario2994, history, 7 years ago, In English
Discrepancy in performance depending on compiler While trying to squeeze my solution of [problem:1336E2] into the time limit, I have encountered an unexpectedly large difference in the execution times among the various C++ compilers offered by Codeforces. Since I think it is something worth knowing, I am sharing this discovery. Consider the following minimal working example (it generates $2N=30$ random $56$-bits numbers and computes the sum of the bits of the xors of all the subsets of the $30$ numbers). <spoiler summary="Code"> ~~~~~ #pragma GCC optimize ("unroll-loops") #pragma GCC target("sse3,sse4") #include <assert.h> #include <stdlib.h> typedef unsigned long long ULL; ULL rand_short() { // 8 bits return rand() & ((1<<8)-1); } ULL rand_ull() { // 56 bits ULL res = 0; for (int i = 0; i < 7; i++) res = (res<<8)|rand_short(); return res; } int main() { srand(123); const int N = 15; ULL a[N], b[N]; for (int i = 0; i < N; i++) a[i] = rand_ull(), b[i] = rand_ull(...
~~~~~ #pragma GCC optimize ("unroll-loops") #pragma GCC target("sse3

Full text and comments »

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

76.
By wuhudsm, history, 22 months ago, In English
TheForces Round #39 (1000-Forces) Editorial [A](https://codeforces.me/gym/105672/problem/A) Idea:[user:FP7317,2025-01-23] <spoiler summary="solution"> ### Problem Description Since the constraints are small, you only need to simulate this process. You are tasked with finding the minimum number of bandages required to defeat a dragon using a sword. The sword deals: - **1 damage** if the i-th attack is **not divisible by 3**. - **2 damage** if the i-th attack is **divisible by 3**. If your health will becomes less than $0$ when the dragon attack you (in other words, your hp is less than $k$) , you must use a bandage. </spoiler> <spoiler summary="code(C++)"> ```cpp void solve(){ int h,k,n;cin>>h>>k>>n; int ans = 0, l = k, r = 1; while(h > 1){ r++; k -= n; if(k <= 0){ k = l - n; ans++; } if(r % 3 == 0){ h-=2; }else{ h--; } } cout<<ans<<endl; } ``` </spoiler> ...
#pragma GCC optimize("unroll-loops") #pragma gcc optimize("Ofast") #pragma GCC optimization

Full text and comments »

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

77.
By vovuh, history, 9 years ago, In English
Codeforces Round #486 (Div. 3) Editorial [problem:988A] <spoiler summary="Tutorial"> [tutorial:988A] </spoiler> <spoiler summary="Solution (Vovuh)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; set<int> el; vector<int> ans; for (int i = 0; i < n; ++i) { int x; cin >> x; if (!el.count(x)) { ans.push_back(i); el.insert(x); } } if (int(ans.size()) < k) { cout << "NO\n"; } else { cout << "YES\n"; for (int i = 0; i < k; ++i) cout << ans[i] + 1 << " "; cout << endl; } return 0; } ~~~~~ </spoiler> [problem:988B] <spoiler summary="Tutorial"> [tutorial:988B] </spoiler> <spoiler summary="Solution (Vovuh)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin ...
~~~~~ //#pragma comment(linker, "/stack:200000000") //#pragma GCC optimize("Ofast") //#pragma

Full text and comments »

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

78.
By willy108, history, 4 years ago, In English
Teamscode Spring 2023 Editorial This is the editorial for a recent contest [Teamscode](https://www.teamscode.org/). The problems are open for upsolving on [this gym](https://codeforces.me/gym/104287). Problems were prepared by [user:oursaco,2023-04-06], [user:dutin,2023-04-06], [user:thehunterjames,2023-04-06], [user:Bossologist,2023-04-06], [user:Esomer,2023-04-06], and me. ### [A. What do you do when the contest starts? Are you busy? Will you solve Bingo?](https://codeforces.me/gym/104287/problem/A) <spoiler summary = "Editorial"> <spoiler summary = "Are you busy?"> 1. WorldEnd/SukaSuka 2. Bocchi the Rock </spoiler> <spoiler summary = "No Sweep"> 1. Thomas </spoiler> <spoiler summary = "Multiplication Table"> 1. Lycoris Recoil </spoiler> <spoiler summary = "Greatest Common Multiple"> 1. Bokuben </spoiler> <spoiler summary = "A Certain Scientific Tree Problem"> 1. A Certain Scientific Railgun </spoiler> <spoiler summary = "Two and Three"> 1. Quintessential Quintluplets...
```c++ #pragma GCC optimize("O3") #pragma GCC optimization ("unroll, ```c++ #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx

Full text and comments »

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

79.
By Vladosiya, history, 4 years ago, In English
Codeforces Round #811 (Div. 3) Editorial [problem:1714A] Idea: [user:Vladosiya,2022-08-03] <spoiler summary="Tutorial"> [tutorial:1714A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> #define int long long #define pb emplace_back #define mp make_pair #define x first #define y second #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(143); const int inf = 1e15; const int M = 1e9 + 7; const ld pi = atan2(0, -1); const ld eps = 1e-6; void solve(){ int n; cin >> n; int time, h, m; cin >> h >> m; time = 60 * h + m; int ans = 24 * 60; for(int i = 0; i < n; ++i){ cin >> h >> m; int t = 60 * h + m - time; if(t < 0) t += 24 * 60; ans = min(ans, t); } cout << ans / 60 << " " << ans % 60; } bool multi = true; signed main() { int t = 1; if (multi)cin >> t; for (; t; --t) { ...
~~~~~ #pragma GCC optimize("O3","unroll-loops") #pragma GCC target

Full text and comments »

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

80.
By SHaF3Y, history, 6 months ago, In English
A Sneaky C++ Bug: AC on Clang, WA on GCC **I used Ai to format the Blog** While solving the problem [TTM on SPOJ](https://www.spoj.com/problems/TTM/) using a Persistent Segment Tree, I ran into a very frustrating bug My code was logically correct, yet I was getting completely different verdicts depending on the compiler: * **Accepted** on `C++14 (Clang)` * **Wrong Answer** on `C++14 (GCC)` After a long debugging, the issue turned out to be caused by **unspecified evaluation order** [Code](https://ideone.com/uXMeOB) Here is the problematic line: ```cpp // 't' is the current version number of the Persistent Segment Tree if (op == 'C') { int l, r, d; cin >> l >> r >> d; --l, --r; // The fatal line: pst.roots[++t] = pst.update(t, l, r, d); } ``` ## What’s the Problem? In **C++14 and older**, the C++ standard does **not specify** the evaluation order of the operands of the assignment operator (`=`) That means the compiler is free to evaluate either: * the left-hand s...
A Sneaky C++ Bug: AC on Clang, WA on GCC, # How GCC Evaluated It (Left-to-Right) → WA, * **Accepted** on `C++14 (Clang)` * **Wrong Answer** on `C++14 (GCC)`, GCC evaluated the **left-hand side first**:

Full text and comments »

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

81.
By k1r1t0, history, 3 years ago, In English
TheForces Round #15 Editorial <spoiler summary="Problem A"> Save the position of each character in the corresponding vector, and then select the smallest value each time. That way, all strings can be generated. The complexity is $\Theta(n|c|^2)$, we can also use the priority queue do it in $\Theta(n|c|\log|c|)$. <spoiler summary="Code"> ~~~ #include<bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast","inline","-ffast-math") #pragma GCC target("avx,sse2,sse3,sse4,mmx") const int MOD=998244353; void Delta() { string s,answer;cin >> s; vector<vector<int>> Q(26,vector<int>{}); for(int i=0;i<(int)s.size();++i) Q[s[i]-'a'].push_back(i); for(int i=0;i<26;++i) reverse(Q[i].begin(),Q[i].end()); while(true) { bool flag=true; for(int i=0;i<26;++i) if(!Q[i].empty()) flag=false; if(flag) break; vector<bool> Flag(26,false); string temp; for(int j=0;j<26;++j) { int mnidx=-1,mnvalue=2147483647; for(in...
~~~ #include using namespace std; #pragma GCC optimize

Full text and comments »

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

82.
By yeputons, 16 years ago, translation, In English
One more GCC bug (#323) Test code that I've created on contest:<br><a href="http://pastebin.com/jvkUcZx3">http://pastebin.com/jvkUcZx3</a><br>I think that function should return the same results if it calles with byte-to-byte equas parameters.<br>But in this case they are distinct.<br><strike>There is one more test program from MaxBuzz:<br></strike><span class="comment-content-18020"><div class="from-renderer"><strike>#include &lt;cstring&gt;</strike><div><strike>#include &lt;cstdio&gt;</strike></div><div><strike><br></strike></div><div><strike>int f(int x) { return 1 &lt;&lt; x; }</strike></div><div><strike><br></strike></div><div><strike>int main() {</strike></div><div><strike><span class="Apple-tab-span" style="white-space: pre;"> </span>for (int i = 0, j = 42; i &lt; 1000000; ++i)</strike></div><div><strike><span class="Apple-tab-span" style="white-space: pre;"> </span>if (!memcmp(&amp;i, &amp;j, sizeof(int)))&nbsp;</strike></div><div><strike><span class="Apple-tab-span" style="white-space: pre;"> </sp...
One more GCC bug (#323), outcomes: GCC - WA14 (240112), MSVC++ - OK (240115). Problem B from CF#49., >COLLECT_LTO_WRAPPER=c:/soft/mingw/bin/../libexec/gcc /mingw32/4.5.0/lto-wrapper.exe Target, COLLECT_GCC=C:\Soft\MinGW\bin\gcc.EXE COLLECT_LTO_WRAPPER=c:/soft/mingw/bin/../libexec/gcc

Full text and comments »

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

83.
By dvb1r, history, 6 months ago, translation, In English
Codeforces Round 1103 (Div. 3) Editorial [problem:2236A] Idea: [user:arsen1y,2026-06-13] <spoiler summary="Tutorial"> [tutorial:2236A] </spoiler> <spoiler summary="Solution (arsen1y)"> ~~~~~ #include <bits/stdc++.h> #define int long long using namespace std; const int INF = (int) 1e18; int32_t main() { std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int _; cin >> _; while (_--) { int n; cin >> n; vector <int> a(n); int mx = -INF; int mn = INF; for (int i = 0; i < n; ++i) { cin >> a[i]; mx = max(mx, a[i]); mn = min(mn, a[i]); } cout << mx - mn + 1 << "\n"; } return 0; } ~~~~~ </spoiler> [problem:2236B] Idea: [user:eyfxrby,2026-06-13] <spoiler summary="Hint"> Try to find a property that does not change during operations. </spoiler> <spoiler summary="Tutorial"> [tutorial:2236B] </spoiler> <spoiler summ...
~~~~~ //#pragma GCC optimize("Ofast") //#pragma GCC

Full text and comments »

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

84.
By -14, history, 5 years ago, In English
Incredible bug found in __gnu_cxx::rope Today when I took part in the Round #740 solving problem [D. Top-Notch Insertions](https://codeforces.me/contest/1558/problem/D), [my submission](https://codeforces.me/contest/1558/submission/126903561) failed on test 2 without knowing why. After asserting I found that rope contains unwanted contents and I didn't fix the problem during the contest. However, when I replace all `__gnu_cxx::rope.erase(x)` into `__gnu_cxx::rope.erase(x, 1)`, my code works fine (idk if it will pass system test or not; at least, it passes asserting that all elements are rolled back to the initial state). Then! I found it unbelievable to see the following code from [here](http://www.aoc.nrao.edu/php/tjuerges/ALMA/STL/html-4.1.2/rope-source.html#l02310): ![ ](/predownloaded/ad/58/ad5833f2cffab1ebc845091a0cefe4e25cb2533c.png) Look at the line 2318, comments: `Erase, single character`. However, it calls `erase(__p, __p + 1);`, who will erase `__p + 1` characters starting from the position `__p...
**UPD**: I've submitted the [bug](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102048) togcc.

Full text and comments »

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

85.
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 #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

86.
By natalina, history, 3 years ago, translation, In English
Codeforces Round #933 (Div. 3) Привет, Codeforces! В [contest_time:1941] начнётся [contest:1941]. В этом раунде вам будет предложено **7 задач**, посвященных приключениям неугомонного математика, программиста и просто забавного персонажа по имени **Рудольф** и его брата Бернарда и **2 часа 15 минут** на их решение. Задачи подобраны по сложности так, чтобы составить интересное соревнование для участников с рейтингами до 1600. Однако все желающие, чей рейтинг 1600 и выше, могут зарегистрироваться на раунд вне конкурса. Раунд пройдет по правилам образовательных раундов. Во время раунда задачи будут тестироваться на предварительных тестах, а после раунда будет 12-ти часовая фаза открытых взломов. Мы постарались сделать приличные тесты и тоже будем расстроены, если у многих решения будут падать на взломах после окончания раунда. **Штраф** за неверную попытку в этом раунде будет равняться **10 минутам**. [Напоминаем](https://codeforces.me/blog/entry/59228), что в таблицу официальных результатов попадут тол...
(GCC 6-32) and C++17 (GCC 7-32)., ://codeforces.com/blog/entry/126654)), временно доступны только следующие C++ компиляторы: C++14 (GCC 6

Full text and comments »

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

87.
By _Na2Th, history, 9 years ago, In English
Speed up GCC Compile time This is a tip for C++ programmers who use the bits header to include every library from C++. ~~~~~ #include <bits/stdc++.h> ~~~~~ Even more so with C++11, it may take some time for it to compile on your machine. I speak by experience: it took me more than 4s to compile every single time. This would drive me crazy during contests. I know it works on linux with gcc. I would guess it works on any unix with gcc, but I really don't know. The solution I offer here is to [precompile the headers](https://en.wikipedia.org/wiki/Precompiled_header), and avoid processing every header file every time. I'll explain by example, showing how I would prepare for the upcoming contest, round 429. The first thing to do is to make the folder I'll leave my code in, and copy the template file I have into it. ~~~~ mkdir cf429 cp temp.cpp cf429/ ~~~~ The template goes something like ~~~~ #include "bits/stdc++.h" #define mt make_tuple using namespace std; int main(){ ...
Speed up GCC Compile time, I know it works on linux with gcc. I would guess it works on any unix with gcc, but I really don't

Full text and comments »

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

88.
By Gol_D, history, 5 years ago, In English
Codeforces Round #762 (Div. 3) Editorial [problem:1619A] Idea: [user:MikeMirzayanov,2021-12-21] <spoiler summary="Tutorial"> [tutorial:1619A] </spoiler> <spoiler summary="Solution"> ~~~~~ #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) { string s; cin >> s; bool ok = true; if (s.length() % 2 == 0) { forn(i, s.length() / 2) if (s[i] != s[i + s.length() / 2]) ok = false; } else ok = false; cout << (ok ? "YES" : "NO") << endl; } } ~~~~~ </spoiler> [problem:1619B] Idea: [user:MikeMirzayanov,2021-12-21] <spoiler summary="Tutorial"> [tutorial:1619B] </spoiler> <spoiler summary="Solution"> ~~~~~ #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) { ...
/*#pragma GCC optimize("Ofast") #pragma GCC optimize("no-stack-protector") #pragmaGCC optimize

Full text and comments »

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

89.
By 4qqqq, history, 4 years ago, In English
Codeforces Round #837 (Div. 2) Editorial We apologize for the delay in editorial of the tasks. [A. Hossam and Combinatorics](https://codeforces.me/contest/1771/problem/A) Idea: [user:_HossamYehia_,2022-12-14] <spoiler summary="Tutorial"> [tutorial:1771A] </spoiler> <spoiler summary="Solution(_HossamYehia_)"> ~~~~~ #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int n, a[N]; int main() { #ifndef ONLINE_JUDGE freopen("input.in", "r", stdin); #endif int t; scanf("%d", &t); while(t--){ scanf("%d", &n); for(int i = 0 ; i < n ; ++i) scanf("%d", a + i); sort(a, a + n); if(a[0] == a[n - 1]){ printf("%lld\n", (1LL * n * (n - 1LL))); continue; } int mn = 0, mx = n - 1; while(a[0] == a[mn]) ++mn; while(a[n - 1] == a[mx]) --mx; long long l = mn; long long r = n - mx - 1; ...
#pragma GCC optimize("Ofast") #pragma GCC optimize("fast-math") //#define _FORTIFY_SOURCE 0, bs& operator^=(bs &other) { #pragma GCC ivdep for (int i = 0; i < _size; ++i, ~~~~~ #pragma optimize("SEX_ON_THE_BEACH") #pragma GCC optimize("unroll-loops") #pragmaGCC

Full text and comments »

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

90.
By ssvb, 5 years ago, In English
$O(N^2)$ solution to Facebook Hacker Cup 2021 Round 1 problem A2 (part one) Right after the end of Facebook Hacker Cup 2021 Round 1, [user:wjomlex,2021-09-25] posted the following [comment](https://codeforces.me/blog/entry/94726?#comment-839269) in the discussion section under the announcement blog: > A common issue was people writing O(N^2) solutions to problem A when O(N) solutions are necessary. You won't be able to run an O(N^2) solution in 6 minutes when N = 800,000. But is this really true? Challenge accepted! ##### Problem A1 <div> <spoiler summary="Spoiler"> First of all, here is an $O(N)$ solution for [problem A1](https://www.facebook.com/codingcompetitions/hacker-cup/2021/round-1/problems/A1): <spoiler summary="Spoiler"> ~~~~~ #include <iostream> #include <vector> #include <stdint.h> using namespace std; /* * This is a solution for problem A1. Time complexity: O(N) * Characters in the input buffer are remapped: 'F' => 0, 'X' => 1, 'O' => 2 */ static int32_t solve_a1(const int8_t *arr, int n) { int32_t ans = 0, h...
// #pragma GCC optimize("O3,unroll-loops") // #pragma GCC target("avx,avx2,sse,sse2,sse3,sse4

Full text and comments »

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

91.
By wuhudsm, history, 20 months ago, In English
Code Release for TheForce Round #42 Top 10 Hello, Codeforces. Today, as the main manager of a contest, I have decided to release the code for [TheForce Round # 42](https://codeforces.me/gym/105846) Top 10. The reason for this decision is that during the middle of the contest, we noticed unusual standings: ![ 2025-04-18 000415.png](https://s2.loli.net/2025/04/18/inqucELoWUXfOra.png) As a convention of codeforces, the code of all participants after the contest will be made public. I have decided to do the same thing here, and I believe that if you are a normal and honest participant, it will not infringe upon any of your rights. Also, we are checking the code of the participants and making cautious judgments. The allocation of prizes and the calculation of TheForce Rating will be delayed. Sorry for any inconvenience caused. We sincerely hope to maintain a fair and honest competitive environment for all participants. Integrity is the cornerstone of programming contests, and we believe that upholding these values...
#ifdef ONLINE_JUDGE #include #pragma GCC optimize("Ofast,unroll-loops,inline

Full text and comments »

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

92.
By ODT, history, 9 years ago, In English
Codeforces Round #449 Editorial [897A &mdash; Scarborough Fair](http://codeforces.me/contest/897/problem/A) By [user:mcfx,2017-12-04] For every $i$ in range $[l,r]$, if $c_i$ is $c_1$ then change it into $c_2$... Because $n, m$ are all very small, $O( nm )$ can easily pass it. PS. You can use binary search tree to solve it in $O( m\log n )$ time. [897B &mdash; Chtholly's request](http://codeforces.me/contest/897/problem/B) By [user:mcfx,2017-12-04] The $k$-th smallest zcy number is $conn(str(k),rev(str(k)))$, where $str$ denotes the decimal representation of a positive integer as a string, $conn$ denotes the concatenation two strings, and $rev$ denotes the reverse of a string. Then go over the smallest $k$ such numbers and sum them up to obtain the answer. [896A &mdash; Nephren gives a riddle](http://codeforces.me/contest/896/problem/A) By [user:mcfx,2017-12-04] $f(n)=str_1+f(n-1)+str_2+f(n-1)+str_3$. First we can compute the length of $f(n)$ for all possible $n$. For a pair of $(n...
In all the contests I've attended, pragma GCC was not allowed to be used...

Full text and comments »

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

93.
By MikeMirzayanov, 12 years ago, translation, In English
PBOX — simple package manager for Windows (written and used in Codeforces) <a href="http://pbox.me"><img src="http://assets.codeforces.com/images/pboxme.png" style="margin:0 1em 1em 1em;float:right;"/></a> Hello, Codeforces! As you know the Linux package managers make life easier for users and administrators. In the Windows world, this is much worse, although there are some tools (in Windows 10 it will be much better): nuget, chocolatey, wpkg and others. Maintaining Codeforces testing servers, computers of Programming Competitions Training Center of Saratov SU, installing workstations for different olympiads I finally got tired to write a variety of bat-files and decided to regularize the process. [Chocolatey](https://chocolatey.org) makes good help, but in the details it turned out that it can't used in some cases: you can not specify the installation directory, there is no support for private repositories, lack of some packages, Chocolatey packages do not contain installers but only links for them (if package's official is down, one can't instal...
-gcc`. По-умолчанию установит в %HOMEDRIVE%\Programs\mingw-tdm-gcc, пропишет в PATH несколько, Do you want to install exactly the same g++ as Codeforces has? Just run `pbox install mingw-tdm-gcc

Full text and comments »

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

94.
By MrLolthe1st, 2 years ago, translation, In English
Разбор Codeforces Round 990 (Div. 2 + Div. 1) ### Div2A Alyona is happy when there are no unfinished layers &mdash; that is, in front of her is a perfect square with odd side length. Since the order of pieces is fixed, it is enough to keep track of the total current size $s$ of the puzzle, and after each day check, if the $s$ is a perfect square of an odd number. The easiest way to do that is to create an additional array containing $1^2, 3^2, 5^3, ..., 99^2$, and check after each day, whether $s$ is in this array. <spoiler summary="Code"> ~~~~~ NT = int(input()) sqs = set() k = 1 while k * k <= 100 * 1000: sqs.add(k * k) k += 2 for T in range(NT): n = int(input()) a = list(map(int, input().split())) answer = 0 cursum = 0 for t in a: cursum += t if cursum in sqs: answer += 1 print(answer) ~~~~~ </spoiler> ### Div2B Find the character which appears the lowest number of times &mdash; if tied, take the earlier character in the alphabet. Find the character which appears the highe...
#pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

Full text and comments »

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

95.
By Vladosiya, history, 2 years ago, In English
Codeforces Round 966 (Div. 3) Editorial [problem:2000A] Idea: [user:senjougaharin,2024-08-14] <spoiler summary="Tutorial"> [tutorial:2000A] </spoiler> <spoiler summary="Solution"> ~~~~~ for _ in range(int(input())): a = int(input()) if 102 <= a <= 109 or 1010 <= a <= 1099: print("YES") else: print("NO") ~~~~~ </spoiler> [problem:2000B] Idea: [user:myav,2024-08-14] <spoiler summary="Tutorial"> [tutorial:2000B] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; vector<int>a(n); for(auto &i : a) cin >> i; int left = a[0], right = a[0]; for(int i = 1; i < n; i++){ if(a[i] + 1 == left) left = a[i]; else if(a[i] - 1 == right) right = a[i]; else { cout << "NO\n"; return; } } cout << "YES\n"; } int main(){ int t; cin >> t; while (t--) { solve(); } return 0; ...
~~~~~ #pragma GCC optimize("O3,unroll-loops")

Full text and comments »

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

96.
By AquaMoon, 3 years ago, In English
Harbour.Space Scholarship Contest 2023-2024 (Div. 1 + Div. 2) Editorial Thank you for participation and we hope you enjoy this round ヽ(^ o ^)/. During the contest, there was a small issue in problem D. For those affected, we have skipped your duplicate submissions (if your duplicate submissions were not skipped, please let us know). We apologize again for any inconvenience caused. In addition, we are honored to invite you to our unofficial round tomorrow (*╹▽╹*) [Invitation to TheForces Round #22 (Interesting-Forces)](https://mirror.codeforces.com/blog/entry/119771) ### [1864A-Increasing and Decreasing](https://mirror.codeforces.com/contest/1864/problem/A) Idea : [user:wuhudsm,2023-08-27] <spoiler summary="Tutorial"> We use the following greedy construction: For all $i$ ($1<i<n$), set $a_i=a_{i+1}-(n-i)$. If $a_2-a_1 \geq n-1$, we've found a solution, otherwise there is no solution. Proof. Assume there's a solution which includes an index $i$ ($1<i<n$) such that $a_{i+1}-a_i>n-i$. We can make $a_j:=a_j+\Delta$ for all $j$ ($2 \le j ...
``` #include using namespace std; #pragma GCC optimize("Ofast","inline","-ffast

Full text and comments »

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

97.
By Echp0chmak, history, 3 years ago, In Russian
[Перевод] Введение в GCC прагмы Это перевод [статьи](https://codeforces.me/blog/entry/96344) за авторством [nor](https://codeforces.me/profile/nor), на авторские права не претендую. ## Введение Какое то время назад [автор статьи](https://codeforces.me/profile/nor) и [ToxicPie9](https://codeforces.me/profile/ToxicPie9) сделали и запостили мем: ![img](https://web.archive.org/web/20240206143804im_/https://codeforces.me/predownloaded/f9/1a/f91a4a1cd9da1af1b944492a5f836221ced2d8dd.png) На удивление, достаточно много людей не до конца поняли его: в сообществе до сих пор много заблуждений насчет прагм. Большинство пользователей C++ на Codeforces пишут в начале каждой посылки прагмы, но, как мне кажется, мало кто полностью понимают, как именно работают прагмы; люди просто верят, что после добавления прагм код будет работать не хуже и успокаиваются на этом. На самом деле, прагмы &mdash; что-то из разряда черной магии и их используют как правильно, так и неправильно в соревновательном сообществе. Большинств...
[Перевод] Введение в GCC прагмы, ```#pragma GCC target("bmi2") ```., оптимизации. Синтаксис такой: ``` #pragma GCC optimize (option, option2, ...)```, ## В чем смысл "```#pragma GCC optimize```"?, ## Что такое "#pragma GCC target"?, `#pragma GCC optimize "Ofast"` и `\#pragma GCC optimize "-Ofast"` тоже работают. Также работают, `#pragma GCC push_options`, `#pragma GCC pop_options`: эти прагмы позволяют добавлять-удалять, ``` #pragma GCC optimize ("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") ```, ``` #pragma GCC optimize(" unroll-loops") #pragma gcc optimize("Ofast") #pragma GCC optimization, ``` #pragma GCC optimize("O3","unroll-loops") ```, ``` #pragma GCC optimize("O3,unroll-loops") ```, ``` foo.cpp:2: warning: ignoring ‘#pragma gcc optimize’ [-Wunknown-pragmas] 2 | #pragmagcc, ```c++ #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") ```, ~~~~~ #pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt") ~~~~~, В дальнейшем будут обсуждаться только оптимизации на GCC компиляторах; на остальных платформах и, В общем и целом, есть две главных причины, по которым можно использовать ```#pragmaGCC target```:, Полный список поддерживаемых флагов можно найти [здесь](https://gcc.gnu.org/onlinedocs/gcc/Optimize, Судя по [официальной документации по GCC прагмам](https://gcc.gnu.org/onlinedocs/gcc/Function

Full text and comments »

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

98.
By wuhudsm, 3 years ago, In English
TheForces Round #19 (Briefest-Forces) Editorial [A](https://codeforces.me/gym/104455/problem/A) <spoiler summary="code"> ``` #include<bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast","inline","-ffast-math") #pragma GCC target("avx,sse2,sse3,sse4,mmx") #define int long long const int MOD=998244353; void Delta() { int a,b,c,d; cin >> a >> b >> c >> d; cout << (a+b>c+d?"YES":"NO") << endl; } signed main() { ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); int T;cin >> T; while(T--) Delta(); } ``` </spoiler> <spoiler summary="solution"> The probability of Alice's winning is strictly higher than Bob's iff $l_1+r_1>l_2+r_2$. <spoiler summary="Why?"> Lemma1:The distribution of scores for two dice rolls is symmetrical, with the axis of symmetry being $l+r$. For example,for $[2,4]$,the distribution of scores is $4,5,5,6,6,6,7,7,8$. Lemma2:For two intervals with the same axis of symmetry(i.e. $l1+r1=l2+r2$),Alice's probability of losing is always equal t...
``` #include using namespace std; #pragma GCC optimize, #include using namespace std; #pragma GCC optimize("Ofast","inline","-ffast-math, ``` #include using namespace std; #pragma GCC optimize("Ofast","inline","-ffast

Full text and comments »

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

99.
By Gassa, history, 8 years ago, translation, In English
Язык D в спортивном программировании Всем привет! Недавно участнику [user:yosupo,2018-07-28] задали [вопрос](/blog/entry/51923?#comment-446901) о том, в чём преимущества [языка программирования D](https://dlang.org) в соревнованиях перед языком C++. Я регулярно использую D в соревнованиях (и при подготовке задач) с 2014 года, иногда вполне успешно (например, программа на D принесла мне победу в [AZsPCs: Alphabet City](http://azspcs.com/Contest/AlphabetCity/Standings)). Так что хочу поделиться своим опытом. Постараюсь ограничиться только тем, что имеет значение для соревнований. Общее ощущение такое. На D можно писать как на чистом C, когда нужен полный контроль над происходящим. А можно &mdash; как на Питоне, используя довольно мощную библиотеку. При этом D &mdash; компилируемый язык, так что в обоих случаях производительность сравнима с C++. Кроме того, после написания программы её гораздо проще отладить, чем аналогичную программу на C++. В качестве примера давайте посмотрим на два решения одной ...
GCC.

Full text and comments »

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

100.
By snapdragon3101, 7 years ago, In English
CP Editor: An Editor for Competitive Programming This blog is outdated. See https://cpeditor.org ================== Hi Guys! For the past couple of weeks, I was working on a new Code Editor for Competitive Programmers. Today, I am happy to present it to you all, the first release of CP Editor. But First, **Why we need a new editor**? There exists so many code editor of all types, written in all languages but all of them are tailored down for Development of Software and none is specially focused for Competitive Programming. As competitive Programmers, we need our Editor to be Fast, Reliable and Something that just works. We focus mostly on correctness of our code and this involves compiling and re-running on sample test cases again and again. CP Editor is Fast written in Native C++ (Qt), Cross-platform (works everywhere), and has all basic features that a competitive programmer needs from an editor. CP Editor takes away your responsibility of compiling the code and running it on your sample test cases. It automatically w...
> So you will need mingW-gcc or clang or msvc on your PATH.

Full text and comments »

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

101.
By greateric, history, 5 months ago, In English
Useless CP Information #7: How to Become an Assembly Bro (Assembly Tutorial Part 1) _If you were ever curious but were confused by the youtube tutorials. I'm going to try to make this as concise and useful as possible. Also, x86 is way easier to code in than ARM and if you disagree, you're wrong. And Intel syntax is better than AT&T syntax_ _This assumes you have a basic understanding of how pointers work in C_ First program & compiling ================== Make a file named `hello.s`: ~~~~~ .intel_syntax noprefix .section .rodata mystring: .ascii "Hello, World!\n" mystring_end: .section .text .globl main .type main, @function main: endbr64 push rbp mov rbp, rsp mov eax, 1 # write mov rdi, 1 # stdout lea rsi, mystring[rip] mov rdx, mystring_end - mystring syscall xor eax, eax leave ret ~~~~~ Compile and run with ~~~~~ $ gcc -o hello hello.s $ ./hello ~~~~~ In assembly, you are writing CPU instructions, so you only have access to low-level things: - Registers: the...
If you look at assembly generated by GCC, you'll see a lot of moves relative to `rbp`. That's, ~~~~~ $ gcc -o hello hello.s $ ./hello ~~~~~

Full text and comments »

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

102.
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>{}>...
Compiled with GCC 9.3.0 using the command `g++ -std=c++2a main.cpp`. This is the execution output

Full text and comments »

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

103.
By lis05, history, 5 years ago, In English
Two(one) easy knapsack tasks (+Solution) Hello codeforces! Try to solve both of the problems from https://codeforces.me/contestInvitation/fcf424afaf5b7a5d01aebf1a908d6ef3589e4fb3. good luck Solution: This is a simple dp problem(very simple), but with a high constraints. Standard knapsack runtime is O(NW), but we can optimize it to run in O(NW/32) using bitset. ~~~~~ #include<bits/stdc++.h> using namespace std; const int W=2e5; bitset<W>b; signed main(){ int n,w; scanf("%d %d",&n,&w); b[0]=1; while(n--){ int a; scanf("%d",&a); b|=(b<<a); } if(b[w])printf("YES\n"); else printf("NO\n"); } ~~~~~ How does it work? `b[k]` contains 0, if it's not possible to get sum `k`, and 1, if it's possible. At start, we set `b[0]` to 1(because we can get sum 0). Next, for each item we left-shift out bitset by a[i]. `new_b=b<<a[i]` After this move, new bitset contains information about what can we get if we will take current item, but it ig...
// very useful pragmas #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #pragma

Full text and comments »

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

104.
By EnDeRBeaT, 3 years ago, In English
[Tool] Graph Debugger Hi, CodeForces! For the past 2 months I have been working on a Graph Debugging tool, which allows you to draw graphs like these with just **TWO** lines of code: ![ ](/predownloaded/42/15/4215be4db6122c5583244a262d651c2dc5ae6b81.png) This is similar to print debugging (when you got a crash somewhere, so you repeatedly recompile the code with `cout << "penis\n";` to see where it failed), but instead it creates a window with the graph, which you can change however you want. It is also a marginally better tool than graph editor from CSAcademy in my opinion, so I would love you guys to try it out. This is not compatible with MacOS because Apple deprecated OpenGL (and even if it wasn't, it would've been kinda annoying to use) ## Building First, build the code from the repo: https://github.com/EnDeRGeaT/graph-debugger If you write in Visual Studio (not Visual Studio Code), follow "For MSVC" part. If you write in anything else, you probably should follow "For GCC/...
anything else, you probably should follow "For GCC/Clang".

Full text and comments »

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

105.
By yak_ex, 16 years ago, In English
A way to use C++ iostream for large input (gcc only) <P><STRONG>Updated:</STRONG> Add note for Cygwin environment.<BR><STRONG>Updated</STRONG>: Add result on FreeBSD<STRONG> </STRONG><BR></P><P>In programming competition such as Codeforces, reading a large number of inputs is somtimes required, for example, 1500*1500 integers in <A href="http://www.codeforces.com/contest/46/problem/E">Codeforces Beta Round #43 Problem E</A>. I used iostream(cin) in the competition and got TLE. After the competition, I saw some comments that cin caused TLE. After I replaced cin with scanf, I got AC. So, it is said "For large input, use cstdio instead of iostream." However I believe C++ users want to use iostream. Can't we avoid the guideline?</P><P><STRONG>Short answer:</STRONG></P><P>I found one promising way. Unfortunately, it is applicable not to VC but to gcc. Call std::ios_base::sync_with_stdio(false) at the beginning of your code. Here is the graph to show performance comparison among iostream with the call, without the call and cstdio, <EM><STRONG>...
A way to use C++ iostream for large input (gcc only), * Compiler: gcc 4.3.4 on Cygwin 1.7.7 * FreeBSD * CPU: PentiumM 1.3GHz, I found one promising way. Unfortunately, it is applicable not to VC but to gcc . Call std

Full text and comments »

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

106.
By willy108, history, 3 years ago, In English
Teamscode Spring 2024 Contest Official Editorial Sorry for the long wait. These problems were brought to you by [user:esomer,2024-04-05], [user:danx,2024-04-05], [user:dutin,2024-04-05], [user:jay_jayjay,2024-04-05], [user:oursaco,2024-04-05], [user:superhelen,2024-04-05], [user:thehunterjames,2024-04-05], [user:willy108,2024-04-05], and [user:yash_9a3b,2024-04-05]. Also, massive thanks to [user:omeganot,2024-04-05] for his [unofficial editorial](https://codeforces.me/blog/omeganot) (which was posted a lot sooner than ours). [Novice A/](https://codeforces.me/gym/105066/problem/A)[Advanced A: It's Time to Submit](https://codeforces.me/gym/105067/problem/A) ================== <spoiler summary="Solution"> Both "YES" and "NO" are consistent answer (as long as exactly one of them is the answer). If you print "YES" and get AC, you are getting AC by printing the sample output. If you print "NO" and get AC, you are getting AC by not printing the sample output. Never assume just because the carrot is big ... the sample out...
#pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

Full text and comments »

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

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

Full text and comments »

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

108.
By wuhudsm, history, 3 years ago, In English
TheForces Round #20 (7-Problem-Forces) Editorial [A](https://codeforces.me/gym/104471/problem/A) <spoiler summary="code"> ``` #include <bits/stdc++.h> #define int long long #define fi first #define se second using namespace std; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t --> 0) { int n; cin >> n; vector<int> a(n); vector<int> b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; vector<int> ord(n); iota(ord.begin(), ord.end(), 0); sort(ord.begin(), ord.end(), [&](int x, int y) { if (b[x] == b[y]) return a[x] > a[y]; return b[x] == 1; }); int ans = a[0] * b[0]; int suma = 0, sumb = 0; for (int i = 0; i <...
``` #include using namespace std; #pragma GCC optimize

Full text and comments »

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

109.
By wuhudsm, history, 3 years ago, In English
TheForces Round #23 (Balanced-Forces) Editorial [A](https://codeforces.me/gym/104570/problem/A)<br> Problem author: [user:wuhudsm,2023-09-08],[user:bogocubic1,2023-09-08] <spoiler summary="code"> ``` #include <bits/stdc++.h> using namespace std; void test_case() { int a, b, c, n; cin >> a >> b >> c >> n; c = min(c, n / 100); n -= c * 100; b = min(b, n / 10); n -= b * 10; a = min(a, n); n -= a; if (n == 0) cout << "YES\n"; else cout << "NO\n"; } int32_t main() { ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) test_case(); } ``` </spoiler> <spoiler summary="solution"> We only need to use $100$ coins as much as possible first, then $10$ coins as much as possible, and finally $1$ coins. </spoiler> [B](https://codeforces.me/gym/104570/problem/B)<br> Problem author: [user:wuhudsm,2023-09-08] <spoiler summary="code"> ``` #ifndef LOCAL #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx,avx2,sse,sse2,sse3,sse4,popcnt,fma") #endif #include ...
``` #ifndef LOCAL #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx,avx2,sse,sse2

Full text and comments »

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

110.
By Vladosiya, history, 4 years ago, translation, In English
Codeforces Round #834 (Div. 3) Editorial [problem:1759A] Idea: [user:MikeMirzayanov,2022-11-20] <spoiler summary="Tutorial"> [tutorial:1759A] </spoiler> <spoiler summary="Solution"> ~~~~~ full = 'Yes' * 18 t = int(input()) for _ in range(t): if full.find(input()) >= 0: print('YES') else: print('NO') ~~~~~ </spoiler> [problem:1759B] Idea: [user:MikeMirzayanov,2022-11-20] <spoiler summary="Tutorial"> [tutorial:1759B] </spoiler> <spoiler summary="Solution"> ~~~~~ t = int(input()) for _ in range(t): n, s = map(int, input().split()) a = [int(x) for x in input().split()] s += sum(a) sm = 0 cnt = 0 for i in range(1, s + 1): if sm >= s: break sm += i cnt = i if sm != s or max(a) > cnt or cnt <= n: print("NO"); else: print("YES") ~~~~~ </spoiler> [problem:1759C] Idea: [user:Vladosiya,2022-11-20] <spoiler summary="Tutorial"> [tutorial:1759C] </spoiler> <spoiler s...
~~~~~ #pragma GCC optimize("Ofast")

Full text and comments »

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

111.
By HosseinYousefi, history, 8 years ago, In English
Competitive C++ Manifesto: A Style Guide # Competitive C++ Manifesto: A Style Guide There are many style guides for C++ out there, but we can't really use them as competitive programmers. We just want to write our code correctly as fast as possible! Trying to hack people here on codeforces, I realized there is a need for a style guide! Our goal is to write correct, fast, clear and consistent code. > #### Disclaimer > This is not a rulebook. You can integrate parts of it into your coding style. > Don't overthink it, especially during a contest! I'm going to use this guide for myself and to [teach my students](https://in.harbour.space/computer-science/modern-c-programming-hossein-yousefi/). I'm planning to make some good stuff in the future following these principles! Stay tuned! ## Compiler Make use of C++17. Use `-Wall -Wextra -Wshadow` flags for compilation, and try to eliminate all of the warning messages, this will prevent you from having some silly bugs. There are more debugging flags like `-fsanitize=un...
] * [Catching silly mistakes with GCC](https://codeforces.me/blog/entry/15547) by [user:andreyv,2019

Full text and comments »

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

112.
By MohammadParsaElahimanesh, 2 years ago, In English
Rayan 2024 Selection Round Editorial ### &#128075; Salam Codeforces! Here are the step-by-step solutions. Hoping you enjoy them! &#128522; The announcement blog is available [here](https://codeforces.me/blog/entry/136396) and you can also explore all blogs related to Rayan [here!](https://codeforces.me/rayan) #### [problem:2034A] **Idea:** [user:ArshiaDadras,2024-11-26] &mdash; **Preparation:** [user:Amirrzwm,2024-11-26] <spoiler summary="Solution"> - **Step 1:** Prove that for the minimum value of $m$, we must have $m \% a = m \% b = 0$. - **Step 2:** To prove this, show that if $m \% a = m \% b = x > 0$, then $m-1$ will also satisfy the problem's requirements. - **Step 3:** Since $m \ge \min(a , b)$, if $x > 0$, then $m > \min(a , b)$ must hold. Therefore, $m - 1 \ge \min(a , b)$ implies that $m-1$ satisfies the requirements. - **Step 4:** Thus, $m$ must be divisible by both $a$ and $b$. The smallest such $m$ is $lcm(a, b)$ which can be calculated in $O(\log(\max(a, b)))$. </spoiler> <spoiler...
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3") #include

Full text and comments »

113.
By Gol_D, history, 5 years ago, In English
Codeforces Round #756 (Div. 3) Editorial [problem:1611A] Idea: [user:MisterGu,2021-11-26] <spoiler summary="Tutorial"> [tutorial:1611A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { string n; cin >> n; if((n.back() - '0') % 2 == 0) { cout << "0\n"; continue; } if((n[0] - '0') % 2 == 0) { cout << "1\n"; continue; } int count_2 = count(n.begin(), n.end(), '2'); int count_4 = count(n.begin(), n.end(), '4'); int count_6 = count(n.begin(), n.end(), '6'); int count_8 = count(n.begin(), n.end(), '8'); if(count_2 > 0 || count_4 > 0 || count_6 > 0 || count_8 > 0) { cout << "2\n"; continue; } cout << "-1\n"; } return 0; } ~~~~~ </spoiler> [problem:1611B] Idea: [user:MikeMirzayanov,2021-11-26] <spoiler...
/*#pragma GCC optimize("Ofast") #pragma GCC optimize("no-stack-protector") #pragmaGCC optimize

Full text and comments »

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

114.
By Error_Yuan, 4 years ago, In English
Codeforces Round 896 (Div. 1, Div. 2) Editorial [problem:1869A] Author: [user:Error_Yuan,2023-09-03] <spoiler summary="Hint 1"> Indeed at most $\bf 4$ operations will be used. </spoiler> <spoiler summary="Hint 2"> If $r-l+1$ is even, and you do the operation on $[l,r]$ twice, then the subarray $a[l;r]$ will all become $0$. </spoiler> <spoiler summary="Solution"> [tutorial:1869A] </spoiler> <spoiler summary="Implementation"> ```cpp #include <bits/stdc++.h> #define all(s) s.begin(), s.end() using namespace std; using ll = long long; using ull = unsigned long long; const int _N = 1e5 + 5; int T; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; if (n & 1) { cout << "4" << '\n'; cout << "1 " << n - 1 << '\n'; cout << "1 " << n - 1 << '\n'; cout << n - 1 << ' ' << n << '\n'; cout << n - 1 << ' ' << n << '\n'; } else { cout << "2" << '\n'; cout << "1 " << n << '\n'; cout << "1 " << n << '\n'; } return; } int main() ...
ull unsigned long long using namespace std; #pragma GCC optimize("Ofast")

Full text and comments »

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

115.
By GoatTamer, 4 years ago, In English
Invitation to Insomnia Qualifier 2022 Hello Codeforces! Computer Club, MNNIT Allahabad, India is glad to invite you to the annual programming competition of MNNIT, INSOMNIA, which is an ACM-ICPC style team programming contest of 2.5 hours duration held on Codeforces during its annual technical fest Avishkar. The team can consist up to 3 members. <b>Contest Details: </b> <ol> <li> Qualifiers: </li> <ul> <li> Start Time: Wednesday, November 9, 21:00 IST</li> <li> Duration: 2.5 hours</li> </ul> <li> Finals: </li> <ul> <li> Start Time: Sunday, November 13, 12:00 IST</li> <li> Duration: 2.5 hours</li> </ul> </ol> **Top 25** global teams, and **Top 25** teams from MNNIT (based on the result of Qualifiers) will qualify to the Finals. The prize distribution for global teams is mentioned below: <br> ![ ](https://i.imgur.com/dqescfm.png) Teams consisting of MNNIT students only will be eligible for a seperate prize pool. Register your team for the qualifiers here: https://forms.gle/BKsbKfoGzSxC394R8 <br>...
#pragma GCC target ("avx2") #pragma GCC optimize ("O3") #pragma GCC optimize ("unroll-loops")

Full text and comments »

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

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

Full text and comments »

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

117.
By vaaven, history, 18 months ago, In English
Codeforces Round #1031 Editorial [problem:2113A] <spoiler summary="Tutorial"> [tutorial:2113A] </spoiler> <spoiler summary="Code"> ~~~~~ #include <iostream> using namespace std; void solve() { int t, a, b, x, y; cin >> t >> a >> b >> x >> y; auto solve = [&](int t, int a, int b, int x, int y) { int cur = 0; cur += max((t - a + x) / x, 0); t -= max((t - a + x) / x, 0) * x; cur += max((t - b + y) / y, 0); return cur; }; cout << max(solve(t, a, b, x, y), solve(t, b, a, y, x)) << endl; } signed main() { int q = 1; cin >> q; while (q --> 0) solve(); return 0; } ~~~~~ </spoiler> [problem:2113B] <spoiler summary="Tutorial"> [tutorial:2113B] </spoiler> <spoiler summary="Code"> ~~~~~ def solve(): w, h, a, b = map(int, input().split()) x1, y1, x2, y2 = map(int, input().split()) if x1 == x2: if abs(y1 - y2) % b == 0: return "Yes" else: ...
~~~~~ //#pragma GCC optimize("Ofast")

Full text and comments »

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

118.
By pavook, history, 4 years ago, In English
Сравнение производительности разных реализаций дерева отрезков Иногда я задумываюсь, какую реализацию дерева отрезков написать в задаче. Обычно я при помощи метода "пальцем в небо" выбираю какую-то и в большинстве случаев она проходит ограничения. Я решил подвести основу, так сказать базу, под этот выбор и протестировал на производительность 4 разные реализации: <ul> <li> Простой рекурсивный "Разделяй и властвуй" <spoiler summary="Код"> ~~~ struct SimpleRecursiveSegmentTree { unsigned size; private: std::vector<long long> t; void _build(const std::vector<int> &v, unsigned p, unsigned l, unsigned r) { if (r == l + 1) { t[p] = v[l]; return; } unsigned m = (l + r) / 2; _build(v, 2 * p + 1, l, m); _build(v, 2 * p + 2, m, r); t[p] = t[2 * p + 1] + t[2 * p + 2]; } long long _get(unsigned p, unsigned l, unsigned r, unsigned a, unsigned b) const { if (b <= l || r <= a) { return 0LL; ...
I compiled the benchmark with `#pragma GCC optimize("O3")` on GNU GCC 11.3.0, and ran it with the, Я компилировал бенчмарк с `#pragma GCC optimize("O3")` на GNU GCC 11.3.0, запускал его с

Full text and comments »

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

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

Full text and comments »

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

120.
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...
- Workarounds for bad GCC codegen wrt. syscalls with inline assembly (had to read XNU code for that, - Костыли для плохого кодгена GCC при условном вызове сисколлов в hot loop с помощью инлайн, of that* on Linux. Duh. (To Apple fans: your `` sucks because you use libc++. InstallGCC, -за использования libc++. Установите GCC вместе с Linux (brew тоже отстой), перейдите на cstdio или

Full text and comments »

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

121.
By VladProg, 8 years ago, translation, In English
Codeforces Round #499 — editorial [problem:1011A] Author: Mike Mirzayanov ([user:MikeMirzayanov,2018-07-26]). <spoiler summary="Tutorial"> [tutorial:1011A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; string s; cin>>s; sort(s.begin(),s.end()); char last='a'-2; int ans=0; int len=0; for(int i=0;i<n;i++) if(s[i]>=last+2) { last=s[i]; ans+=s[i]-'a'+1; len++; if(len>=k) cout<<ans,exit(0); } cout<<-1; } ~~~~~ </spoiler> [problem:1011B] Author: Mike Mirzayanov ([user:MikeMirzayanov,2018-07-26]). <spoiler summary="Tutorial"> [tutorial:1011B] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; const int N = 100; int main() { int n, m; cin >> n >> m; vector<int> c(N + 1); for (int i = 0; i < m; i++) ...
~~~~~ #pragma GCC optimize("O3") #include

Full text and comments »

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

122.
By bicsi, history, 6 years ago, In English
Automatic pre-compiler for submitting tasks on Codeforces Hello! After seeing the recent hype towards debugging utils and code snippets usage and what not, and due to the fact that I had 30 minutes of free time to spend this afternoon, I decided to write a small Python script that pre-compiles multiple files into one big file for Codeforces submission. The tool is here: https://pastebin.com/c4dS4Pik (Python 3 required) Basically the tool does these steps: - remove the ``#include <bla>`` lines from the code - run the GCC preprocessor on the code - add the ``#include <bla>`` lines back - run some cleanup routine (optional) In order to use this script, copy it somewhere (preferably in your PATH directory), and run it using: ``/path/to/scr.py file.cpp [ARGS]`` The ``ARGS`` are similar to the ones you would give to your ``g++`` command. For example, let's say we have three files: <spoiler summary="FILE: debug.hpp"> ``` #pragma once #ifdef DEBUG int recur_depth = 0; #define dbg(x) {++recur_depth; auto x_=x; --r...
- remove the ``#include `` lines from the code - run the GCC preprocessor on the code - add

Full text and comments »

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

123.
By tokitsukaze, 7 years ago, In English
Codeforces Round #573 Editorial [problem:1191A] Idea: [user:tokitsukaze,2019-02-01] <spoiler summary="Tutorial"> Just enumerating the increment can pass. However, by increasing at most $2$ points, the value of her HP can always become an odd number, and thus the highest possible level is either $A$ or $B$. We can just solve case by case. </spoiler> <spoiler summary="Solution (by Claris)"> ~~~~~ #include<cstdio> int x,i,A;char B; char cal(int x){ x%=4; if(x==0)return 'D'; if(x==1)return 'A'; if(x==2)return 'C'; return 'B'; } int main(){ scanf("%d",&x); A=0; B=cal(x); for(i=1;i<=2;i++){ if(cal(x+i)<B){ A=i; B=cal(x+i); } } printf("%d %c",A,B); } ~~~~~ </spoiler> <spoiler summary="Solution (by tokitsukaze)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int x; cin>>x; if(x%4==0) puts("1 A"); else if(x%4==1) puts("0 A"); else if(x%4==2) puts("1 B"); else if(x%4==3) puts("2 A"); return 0; } ~~~~~ </s...
~~~~~ //#pragma GCC optimize("O3") #include

Full text and comments »

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

124.
By MEDAAA, history, 6 months ago, In English
Counting using symmetry of expectations Hello Codeforces! Today I want to share some thoughts on the magic of symmetry and linearity of expectation. We have all encountered counting problems that seem completely impossible to calculate directly. But there is a beautiful trick: if we use symmetry to convert a pure counting problem into an expected value problem, we unlock the ability to bypass massive formulas and solve the problem elegantly. Before we begin, make sure you are familiar with the basics of: **Expected values (Obviously)** **Indicator variables:** An indicator variable is a simple binary variable that equals 1 if a specific event occurs, and 0 if it does not. The most useful property of an indicator variable is that its expected value is exactly equal to the probability of the event happening ($E[I] = P(I=1)$). This makes them the perfect atomic building blocks for counting complex occurrences. **Linearity of expectation:** the expected value of a sum of random variables is always equal to the sum o...
~~~~~ #include #pragma GCC optimize("Ofast, unroll-loops") #ifdef ONLINE_JUDGE

Full text and comments »

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

125.
By andreyv, 14 years ago, translation, In English
Yet again on C++ input/output Hello! I wish to continue the discussion on C++ input/output performance, which was [started](http://codeforces.me/blog/entry/562) by [user:freopen,2012-09-05] long ago. [user:freopen,2012-09-05] compared the speed of the two common input/output methods in C++: the stdio library, inherited from C (`<stdio>`), and the newer iostreams library (`<iostream>`/…). However, these tests did not account for the fact that there are several important iostreams optimizations which can be used. They have been mentioned more than once on Codeforces ([first](http://codeforces.me/blog/entry/10), [second](http://codeforces.me/blog/entry/4006), [third](http://codeforces.me/blog/entry/4669)). I have written [a program](https://bitbucket.org/andreyv/cppiotest/src/tip/iotest.cpp) that compares performance of the stdio and iostreams libraries with these optimizations turned on. [cut]   **UPD1**: Added information on `_CRT_DISABLE_PERFCRIT_LOCKS`.<br/> **UPD2**: Added `printf()`/`scanf()` ca...
- For MinGW (GCC 4.7.0): http://pastie.org/4680314, - Для MinGW (GCC 4.7.0): http://pastie.org/4680314

Full text and comments »

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

126.
By misteg168, history, 8 months ago, In English
Codeforces Round 1093 (Div. 1, Div. 2) Editorial Thanks everybody for participating in the round! ### [Div2A. Blocked](https://codeforces.me/contest/2220/problem/A) Author: [user:misteg168,2025-12-20] Preparation: [user:misteg168,2025-12-20] <spoiler summary="Hint1"> What happens when there are two equal elements? </spoiler> <spoiler summary="Solution"> [tutorial:2220A] </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (auto &x : a) cin >> x; sort(a.rbegin(), a.rend()); for (int i = 0; i < n-1; i++) if (a[i] == a[i+1]) { cout << "-1\n"; return; } for (auto x : a) cout << x << " "; cout << "\n"; } int main() { int T; cin >> T; while (T--) solve(); } ~~~~~ </spoiler> ### [Div2B. OIE excursion](https://codeforces.me/contest/2220/problem/B) Author: [user:danx,2025-09-20] Preparation: [user:danx,2025-09-20] <spoiler summary="Solution"> [tutorial:2220B] ...
~~~~~ #pragma GCC optimize ("O3") #include using

Full text and comments »

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

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

Full text and comments »

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

128.
By SPyofgame, history, 5 years ago, In English
Count a, b, c satisfy a + b + c <= S and a * b * c <= T for large S, T ### Statement This question is based on bonus of [this problem](https://atcoder.jp/contests/abc214/tasks/abc214_b). We need to count such non-negative integer triple $(a, b, c)$ that satisfy $(0 \leq a + b + c \leq S)$ and $(0 \leq a \times b \times c \leq T)$. Since the result may be very big, you can either use **bignum** or **modulo** $10^9 + 7$ for convention ---------- **Notice that:** - $(0, 0, 1) \neq (0, 1, 0) \neq (1, 0, 0)$ ---------- **Constraint:** - $0 \leq S, T \leq 10^{18}$ - $0 \leq a, b, c$ ---------- **No Time Limit. But expect to be 10 seconds** ---------- **Memory Limit: 1Gb** ---------- **Input:** - A single line contain only two positive **60-bit integers** $S$ and $T$ ($0 \leq S, T \leq 10^{18}$) ---------- **Output:** - Print a single integer, the number of positive tuple satisfy mathematical condition ----------------------------------- **Example:** <spoiler summary="Example 0"> ```css ...
#pragma GCC target ("avx2") #pragma GCC optimization ("O3") #pragma GCC optimization ("unroll

Full text and comments »

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

129.
By chromate00, 4 years ago, In English
STL in CP — Chapter 1-2: Algorithms (Modifying sequence operations) Alas, It's time for another day of STL in CP. Last time we covered the Non-modifying sequence operations, and as you may have expected, we shall cover the Modifying ones this time. The concept is simple- they simply modify a range or a variable (or multiple of them) which you have given to the functions. But the usage? There are something deeper when we think about the details of these functions. In this article, We will cover trivial functions quickly, and then take some time in looking at the ones with more interesting usages. ----------------------------- ### `copy`, `copy_if`, `copy_n`, `copy_backward` These are quite trivial, they do what their names suggest. `copy` copies, `copy_n` copies $n$ elements from the beginning, `copy_backward` does the same thing with `copy` but copies the last element first. Time complexity takes $O(n)$ assignments, so it's $O(n)$ assuming the types you're copying takes $O(1)$ to assign. Otherwise, it's multiplied by their time complexity, obv...
~~~~~ #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx2,popcnt,lzcnt,abm,bmi

Full text and comments »

Tags stl, c++
  • Vote: I like it
  • +13
  • Vote: I do not like it

130.
By MikeMirzayanov, 17 years ago, translation, In English
About the programming languages **This post is no longer relevant; it has become significantly outdated. You should read the post at [https://codeforces.me/blog/entry/121114](https://codeforces.me/blog/entry/121114)**. <p> Later you'll be introduced to the rules of the Codeforces contests, which differ from those of <a href="http://en.wikipedia.org/wiki/ACM-ICPC#Contest_rules">ACM-ICPC</a>, TopCoder, GCJ, and I hope they'll bring some difference to the world of programming competitions. Most of the official competitions will be carried out according to these rules, though there will be more traditional contests. For example, Codeforces Beta Round #1 will be carried out according to the familiar <a href="http://en.wikipedia.org/wiki/ACM-ICPC#Contest_rules">ACM-ICPC</a> rules. For some time testing will be based on Windows, but things might change in future, fortunately, the system supports testing on different platforms, even within one contest. </p> <p> At the present time the ...
UPD: GCC compiler has been added. , UPD: Добавлен чистый C (компилятор gcc).

Full text and comments »

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

131.
By Baraa-Ahmed, 10 months ago, In English
Zaglol FCDS Contest Solutions **[Zaglol Contest &mdash; FCDS level 1:](https://codeforces.me/gym/106350)** Problem [A. Zaglol welcoming](https://codeforces.me/gym/106350/problem/A): <spoiler summary="Solution"> Print **FCDS** </spoiler> <spoiler summary="Code"> ~~~~~ #include <iostream> using namespace std; int main() { cout << "FCDS" << endl; } ~~~~~ </spoiler> Problem [B. Baby Baraa in ALBAIK](https://codeforces.me/gym/106350/problem/B): <spoiler summary="Hint"> Notice that the values of $a_i$ are bounded: $(1 \le a_i \le 100)$. </spoiler> <spoiler summary="Solution"> It is easy to see that the $O(N^2)$ brute-force approach will be too slow for the given constraints. Therefore, we need a faster way to count, for each $i$, how many indices $j > i$ satisfy $(a_i > a_j)$. Since that the values of $a_i$ are bounded: $(1 \le a_i \le 100)$, we can use a frequency array to count how many numbers smaller than a given value appear to its right. We process the array fro...
~~~~~ #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops

Full text and comments »

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

132.
By dmkozyrev, history, 8 years ago, translation, In English
[Tutorial] Полиномиальное хэширование + разбор интересных задач Здравствуйте! Этот пост написан для всех тех, кто хочет освоить полиномиальные хэши и научиться применять их в решении различных задач. Я кратко приведу теоретический материал, рассмотрю особенности реализации и разберу некоторые задачи, среди них: 1. Поиск всех вхождений одной строки длины $n$ в другую длины $m$ за $O(n+m)$ 2. Поиск наибольшей общей подстроки двух строк длин $n$ и $m$ $(n \ge m)$ за $O((n+m \cdot log(n)) \cdot log(m))$ и $O(n \cdot log(m))$ 3. Нахождение лексикографически минимального циклического сдвига строки длины $n$ за $O(n \cdot log(n))$ 4. Сортировка всех циклических сдвигов строки длины $n$ в лексикографическом порядке за $O(n \cdot log(n)^2)$ 5. Нахождение количества подпалиндромов строки длины $n$ за $O(n \cdot log(n))$ 6. Количество подстрок строки длины $n$, являющихся циклическими сдвигами строки длины $m$ за $O((n+m) \cdot log(n))$ 7. Количество суффиксов строки длины $n$, бесконечное расширение которых совпадает с бесконечным расшир...
::uniform_int_distribution` (in cygwin on windows and gnu gcc on linux this set provides almost, `, `std::mt19937`, `std::uniform_int_distribution` (в cygwin на windows и gnu gcc на linux

Full text and comments »

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

133.
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...
Since `gcc` is one of the mostly used C++ compilers in many CP platforms, you can easily see the

Full text and comments »

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

134.
By Hexagons, 2 years ago, In English
OMORI CONTEST Editorial Thank you for joining the [contest](https://codeforces.me/contestInvitation/fc8da6d6845e77adc452e754d3d84c1086148c59) &#128522;. <spoiler summary="How did you find the contest?"> - Great - Good - Average - Bad - Trash </spoiler> <spoiler summary="Which problem is your favourite?"> - SUNNY - AUBREY - HERO - KEL - MARI - BASIL - OMORI </spoiler> #### [A. SUNNY](https://codeforces.me/gym/551481/problem/A) <spoiler summary="Editorial"> <spoiler summary="Problem Tags"> `bijections` `dynamic-programming` </spoiler> <spoiler summary="Hint 1"> Try to find a bijection, meaning try to find another problem such that its solution is equivalent to the original problem but is easier to solve. </spoiler> <spoiler summary="Hint 2"> Try to notice what happens to the difference array of $a$ when Sunny plays a note. </sp...
~~~~ #include using namespace std; #pragma GCC

Full text and comments »

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

135.
By actualtsg, history, 8 months ago, In English
Codeforces please upgrade your C compiler! GCC 5 is too old! GCC 5.1 is too old and slow for today standard! I have encountered so many problem because of it **"qsort" implementation is slow:** - - comment: https://codeforces.me/blog/entry/150510#comment-1342922 - - code 2193D: ([submission:359841071] TLE) ([submission:360069514] Fixed by modifying sort function) - - code 2193F ([submission:360069301] TLE) ([submission:360069436] Fixed by modifying sort function) **"%lf" on printf is not working (scanf is worked), should be "%f" but that for float not double:** - - code 500D: ([submission:364906153] WA) ([submission:364906215] AC after 10 retries figuring out that the problem was `%lf`!) - - comment: you can see on my WA submission that I just printing `2.0` but output always `0.0` for unknown reason :( **sscanf / sprintf is slow:** - - comment: https://codeforces.me/blog/entry/152085#comment-1353829 - - code 2204E: ([submission:367013757] TLE using sscanf/sprintf) ([submission:367016186] AC using manual number -> string ...
Codeforces please upgrade your C compiler! GCC 5 is too old!, Conclusion: The old compiler has a lot of problem! Imagine using unoptimized gcc 5 on 2026 >,< Now

Full text and comments »

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

136.
By Bungmint, history, 5 years ago, In English
Mo's Algorithm with extra backtracking Problem I was trying to solve this problem on CodeChef, [QCHEF](https://www.codechef.com/problems/QCHEF), using Mo's algorithm and realized it is not so simple to come up with a data structure that can save previous results, so that you can simply obtain the result after deletion. I looked up how to maintain previous results, and found this nice comment, [link](https://codeforces.me/blog/entry/7383?#comment-161520), where it describes this abstract notion on how one could have one function, snapshot(), for saving the current results, and another function, rollback() to go back to the previous state. I tried to implement this, code below, but it failed miserably. Any help would be appreciated. UPD: Apparently I had a typo in one of the add functions, and fixing that immediately solved the problem lol. <spoiler summary="Code"> ~~~~~ #pragma GCC optimize("O3") #pragma GCC target("sse4") #include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int...
~~~~~ #pragma GCC optimize("O3") #pragma GCC target("sse4") #include using

Full text and comments »

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

137.
By OtterZ, history, 2 years ago, In English
Some bugs and features looks weird but really exists There are some bugs and features exists while compiling a c++ code,it looks weird but really exists on standard c++ compiler.I'll write down the bugs and features here to remind you to aware of them. # 1.stl::vector:fail to use operator "=". I was trying to implent the merge function of segment tree while solving [the task](https://codeforces.me/contest/1037/problem/H),and the initial code is <spoiler summary="here"> ``` int mrg(int x,int y,int l,int r){ if(x == -1 || y == -1) return x + y + 1; int u = sum.size(); sum.push_back(sum[x] + sum[y]); lc.push_back(-1); rc.push_back(-1); if(l == r) return u; int m = (l + r) >> 1; lc[u] = mrg(lc[x],lc[y],l,m); rc[u] = mrg(rc[x],rc[y],m + 1,r); return u; } ``` ... </spoiler> and found that it will get WA on test #6 using the language `C++14(GCC 6-32)`.Then I found out that the <spoiler summary="code"> ``` lc[u] = mrg(lc[x],lc[y],l,m); rc[u] = mrg(rc[x],rc[y],m + 1,r); ``` ... </spoile...
The bug have been fixed since `C++17(GCC 7-32)`,but if you compile your code using language `C

Full text and comments »

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

138.
By fbrunodr, history, 2 years ago, In English
C++ and VSCode setup on macOS ### Problem to be addressed On Linux it is pretty straightforward to set up the debugger for C++ on VSCode. The workflow is: - Write your code - Go to the [Run and Debug] VSCode section - Click on run active file or something similar - Debug your code On macOS you will run into a lot of silly problems, such as: - Can't find `#include<bits/stdc++.h>` - Installed g++ and got the debugger running, buck can't write input to `std::cin` in the integrated terminal, because it says ~~~~~ Build finished successfully. * Terminal will be reused by tasks, press any key to close it. ~~~~~ and then closes the terminal, making it impossible to write to `std::cin`. After some time browsing the internet I found the solution for all those problems and got my setup working just like on linux. ### Solution Let's brake the solution step by step, from a almost brand new macOS. 1. [Install Homebrew](https://brew.sh) 2. Install g++ (`brew install gcc`) 3. Down...
2. Install g++ (`brew install gcc`)

Full text and comments »

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

139.
By Flamire, history, 2 years ago, In English
EPIC Institute of Technology Round August 2024 (Div. 1 + Div. 2) Editorial [2002A &mdash; Distanced Coloring](https://codeforces.me/contest/2002/problem/A) idea & solution: [user:xcyle,2024-08-12] <spoiler summary="Hint 1"> Consider the case with $n=m=k$. </spoiler> <spoiler summary="Hint 2"> Generalize the solution for all $n,m,k$. </spoiler> <spoiler summary="Tutorial"> It can be shown that for any $k\times k$ subgrid, the colors we use must be pairwise distinct. Thus, we have an lower bound of $\min(n,k)\cdot\min(m,k)$. We can show that this lower bound is indeed achievable by coloring the upper-left $\min(n,k)\cdot\min(m,k)$ subgrid with distinct colors, and copy-pasting it to fill the rest of the grid. Time complexity: $O(1)$. </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int t, n, m, k; int main() { scanf("%d", &t); while (t--) { scanf("%d%d%d", &n, &m, &k); printf("%d\n", min(n, k)*min(m, k)); } return 0; } ~~~~~ </spoiler> [2...
~~~~~ #include #pragma comment(linker, "/stack:200000000") #pragma GCC optimize

Full text and comments »

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

140.
By ramchandra, 6 years ago, In English
Disjoint Sparse Table tutorial ##### Introduction You may have heard of the sparse table data structure, which can do min/gcd queries in $O(1)$ and sum queries in $O(\log n)$. The space complexity and time complexity of constructing a sparse table is $O(n \log n)$. However, the disjoint sparse table data structure can do any type of query such as sum/min/gcd in $O(1)$ with the same $O(n \log n)$ space and time complexity of construction. The operation just needs to be a monoid (i.e. it has an identity element and is associative). Strictly speaking, an identity element is not required, but it allows for empty sum queries which is convenient. ##### Structure Here we assume the array is already resized so that its size is a power of $2$. A disjoint sparse table consists of log n levels numbered from 0 onwards. In the $i$th level, we split the array into $2^i$ blocks. For each block, we store the operation sum of elements between any index in the block and the middle of block. For example, level $0$ would co...
)`, a [GCC extension](https://gcc.gnu.org/onlinedocs/gcc /Other-Builtins.html#:~:text=__builtin_clz

Full text and comments »

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

141.
By Gellyfish, 18 months ago, In English
Codeforces Round 1028 (Div.1, Div.2) Editorial You could tell people didn't seem to like the match very much. I'm sorry I screwed up again ¯\\_(ツ)_/¯ If you're interested, I'd like to share some thoughts I have about this contest. <spoiler summary="sad story"> This time I've been trying my best to make the problems use more varied algorithms instead of just dp problems, but sadly [problem:2115C] was much harder than expected. But it seems like people are complaining more about the narrow time limit, centered on [problem:2116C] and [problem:2115C]. No one realized this before the contest, because none of the tester's code is get TLE except the wrong time complexity. I actually don't see a problem with the Time Limit of [problem:2116C]. Some of you may be puzzled, but let me try to explain this: - The intended solution is $O(\sum n \max(a) + \max(a)^2)$ and does not contain $\log \max(a)$. Computing $\gcd(x, y)$ is not $O(1)$, if you don't preprocess, then it's not unusual to actually get a TLE. - I believe the v...
```c++ #pragma GCC optimize(2) #pragma GCC optimize("Ofast") #pragma GCC optimize("inline","fast

Full text and comments »

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

142.
By dimss, history, 3 years ago, In English
How to speed up the sieve of Eratosthenes by 1.5 times with one line There is such an implementation of the sieve of Eratosthenes: <spoiler summary="usual"> ```c++ const int N = 1e8; bool used[N]; void solve() { ll sum = 0; for (int i = 2; i < N; i++) { if (!used[i]) { sum += i; for (int j = min((ll)INT32_MAX, i * 1ll * i); j < N; j += i) used[j] = true; } } cout << sum << "\n"; } ```</spoiler> Then replace the second line with bitset<N> used; <spoiler summary="bitset"> ```c++ const int N = 1e8; bitset<N> used; void solve() { ll sum = 0; for (int i = 2; i < N; i++) { if (!used[i]) { sum += i; for (int j = min((ll)INT32_MAX, i * 1ll * i); j < N; j += i) used[j] = true; } } cout << sum << "\n"; } ```</spoiler> For comparison, let 's take another linear sieve of Eratosthenes. <spoiler summary="linear"> ```c++ const int N = 1e8; int le[N], primes[N / 10]; ...
Running time table on compiler GNU G++20 11.2.0 (64 bit, winlibs) with ```#pragmaGCC optimize("O3

Full text and comments »

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