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.

vector

Last visit:  8 years ago
Registered:  14 years ago
2.
By Rhodoks, history, 4 years ago, In English
Codeforces Round #810 Editorial Sorry for the late editorial. May this editorial help you. If you have questions, feel free to ask. [problem:1711A] <spoiler summary="hint1."> The minimal weight is at least $1$ since $1$ divides any integer (so $1$ divides $p_1$). </spoiler> <spoiler summary="solution"> Since $k+1$ does not divide $k$, a permutation with weight equal to $1$ is: $[n,1,2,\cdots,n-1]$. </spoiler> <spoiler summary="code"> ~~~~~ #include <bits/stdc++.h> using namespace std; void work() { int n; cin>>n; cout<<n<<' '; for (int i=1;i<n;i++) cout<<i<<' '; cout<<endl; } int main() { int casenum=1; cin>>casenum; for (int testcase=1;testcase<=casenum;testcase++) work(); return 0; } ~~~~~ </spoiler> [problem:1711B] <spoiler summary="hint1."> See the party as a graph. </spoiler> <spoiler summary="hint2."> Divide the vertices into two categories according to their degrees' parity. </spoiler> <spoiler summary="solution"> Let's consider ...
namespace std; typedef pair pll; LL n,m; LL x[MAXN],p[MAXN]; vector diff; pll key, ; int n; char good[MAXN][MAXN]; int lv[MAXN],rv[MAXN]; vector ans;, typedef pair pll; LL n,m; LL x[MAXN],p[MAXN]; vector diff; pll key;, }); vector tmp[2]; int id=1; tmp[0].push_back({l}); tmp[1].push_back({r}); for (int

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

5.
By TLE, history, 8 years ago, In English
Linear Recurrence and Berlekamp-Massey Algorithm **#IjustWantContribution** It seems there isn't any blog about Berlekamp-Massey Algorithm around here, so I decided to go on a try. :P Acknowledgement: Hats off to matthew99 for introducing this algorithm. #### What is 'linear recurrence'? Assuming there is a (probably infinity) sequence $a_0,a_1...a_{n-1}$, we call this sequence satisfies a linear recurrence relation $p_1,p_2...p_m$, iff $\forall i \geq m,~a_i=\sum_{j=1}^m a_{i-j}p_j$. (Obviously, if $m\geq n$ any $p$ can do :P) #### How to calculate k-th term of a linear recurrence? For a polynomial $f(x)=\sum_{i=0}^{t} c_ix^i$, we define $G(f)=\sum_{i=0}^{t} c_ia_i$. Obviously $G$ satisfies $G(f)\pm G(g) =G(f \pm g)$. Because $a_i=\sum_{j=1}^m a_{i-j}p_j$, if we let $f(x)=x^m-\sum_{j=1}^m x^{m-j}p_j$, then $G(f)=0$. Also $G(fx),G(fx^2)...=0$. So $G(fg)=0$ (g is any polynomial). What we want is $G(x^k)$. Because $G(f\lfloor x^k/f\rfloor)=0$, then $G(x^k)=G(x^k \bmod f)$. [cut] We can calculate $x^k \b...
) x=x*a%MOD; a=a*a%MOD; b>>=1; } return x; } namespace linear_seq { inline vector BM, ; } return x; } namespace linear_seq { inline vector BM(vector x) { //ls: (shortest) relation, Why? Consider $f[i]$ as a vector and $v$ as a matrix, then $f[i]=f[i-1]v$, so $f[n]=f[1]v^{n-1

Full text and comments »

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

6.
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...
competitive programming. Probably, I'm wrong. For example, now you can write ` vector v{vector{1, 2, programming. Probably, I'm wrong. For example, now you can write `vector v{ vector{1, 2}};` instead

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

9.
By HosseinYousefi, 12 years ago, In English
C++ Tricks I see lots of programmers write code like this one: ~~~~~ pair<int, int> p; vector<int> v; // ... p = make_pair(3, 4); v.push_back(4); v.push_back(5); ~~~~~ while you can just do this: ~~~~~ pair<int, int> p; vector<int> v; // ... p = {3, 4}; v = {4, 5}; ~~~~~ [cut] [This](http://codeforces.me/blog/entry/10124) is a great C++11 tutorial for those who want to know more about C++11. #### 1. Assign value by a pair of {} to a container I see lots of programmers write code like this one: ~~~~~ pair<int, int> p; // ... p = make_pair(3, 4); ~~~~~ while you can just do this: ~~~~~ pair<int, int> p; // ... p = {3, 4}; ~~~~~ even a more complex `pair` ~~~~~ pair<int, pair<char, long long> > p; // ... p = {3, {'a', 8ll}}; ~~~~~ What about `vector`, `deque`, `set` and other containers? ~~~~~ vector<int> v; v = {1, 2, 5, 2}; for (auto i: v) cout << i << ' '; cout << '\n'; // prints "1 2 5 2" deque<vector<pair<in...
construct value at the end of vector but `push_back` construct it somewhere else and then move it to the, I see lots of programmers write code like this one: ~~~~~ pair p; vector v, This library includes many of libraries we do need in contest like `algorithm`, `iostream`, `vector, What about `vector`, `deque`, `set` and other containers?, When you work with STL containers like `vector`, you can use `move` function to just move container, deque<vector>> d; d = {{{3, 4}, {5, 6}}, {{1, 2}, {3, 4}}}; for (auto i: d, vector v; v = {1, 2, 5, 2}; for (auto i: v) cout << i << ' '; cout << '\n'; // prints, vector> v; v.eb(a,b); // shorter and faster than pb(mp(a,b)), ~~~~~ pair p; vector v; // ... p = make_pair(3, 4); v.push_back(4); v.push_back, ~~~~~ pair p; vector v; // ... p = {3, 4}; v = {4, 5}; ~~~~~, ~~~~~ vector v = {1, 2, 3, 4}; vector w = move(v);, ~~~~~ vector v = {3, 1, 2, 1, 8}; sort(begin(v), end(v), [] (int a, int b) { return a > b, ~~~~~ vector v = {4, 5, 6, 4, 8}; rep(it, end(v), begin(v)) cout << *it, ~~~~~ vector v = {8, 2, 3, 1}; for (auto &it: v) it *= 2; for (auto it: v) cout

Full text and comments »

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

10.
By ATSTNG, history, 7 years ago, In English
[Tutorial] Matroid intersection in simple words **[This article is also available in [Russian](https://codeforces.me/blog/entry/69287?locale=ru)]** Hello, CodeForces. I think that matroids are beautiful and powerful concept, however, not really well known in competitive programming. I’ve discovered matroids at 2019 Petrozavodsk Winter Training Camp. There was a problem that clearly cannot be solved using usual techniques I knew, editorial for this problem was just these three words “just matroid intersection”. Back then it took me more than 2 days of upsolving to find all the information and details I need and implement solution that gets Accepted on this. And it took way longer to actually understand why does it work and exactly how does it work. (I still hesitate in some details.) Of course, it is not hard to google up all the definitions and some related articles, but in my opinion they all are focused more on mathematical part of theory, strict proofs in some not really obvious but short ways, and observing only ke...
<< ground_set[i].vector << "\n"; } }, graphs 4. Linear independence in vector spaces 5. Rank and basis of set of vectors 6. Gaussian, in bipartite graphs 4. Linear independence in vector spaces 5. Rank and basis of set of vectors, **Colorful linear basis.** You are given a set of vectors in some vector space and a color for each, **Linear (algebra) matroid.** Ground set consists of vectors of some vector space. Set of vectors, **Linear matroid.** We have a set of independent vectors in some vector space. We need to check, Matroid is a structure that abstracts and generalizes the notion of linear independence invector, [independent_set[i]].vector); for (int j = 0; j < independent_set.size(); j++) { if (i, bool linear_oracle(int inserted) { return basis.independent_with(ground_set[inserted].vector); }, cin >> ground_set.back().vector; }, return basis_without[wi].independent_with(ground_set[inserted].vector); }, struct GroundSetElement { int color; Z2Vector vector; bool in_independent_set, struct Z2Basis { vector vectors;, vector ground_set; vector independent_set; /// as indexes of ground set

Full text and comments »

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

11.
By -is-this-fft-, history, 5 years ago, In English
[Tutorial] Collection of little techniques #### Introduction There are a number of "small" algorithms and facts that come up again and again in problems. I feel like there I have had to explain them many times, partly because there are no blogs about them. On the other hand, writing a blog about them is also weird because there is not that much to be said. To settle these things "once and for all", I decided to write my own list about about common "small tricks" that don't really warrant a full tutorial because they can be adequately explained in a paragraph or two and there often isn't really anything to add except for padding. This blog is partly inspired by [user:adamant,2022-03-15]'s [blog](48417) from a few years ago. At first, I wanted to mimic adamant's blog structure exactly, but I found myself wanting to write longer paragraphs and using just bolded sentences as section headers got messy. Still, each section is short enough that it would not make much sense to write separate blogs about each of these things. A...
every vertex $u$ you have a vector $dp[u]$ and the length of this vector is at most the number of

Full text and comments »

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

12.
By Golovanov399, 7 years ago, In English
C++ tips and tricks Hello, codeforces. I would like to tell you about some tricks and constructions I use in C++. They are not hidden or anything, moreover, most of them are from stl or maybe well known among software engineers, but I often see codes where something is done by hand in, say, 5 lines, while in stl there is a function which does the same. The things below are filtered by my personal sense of non-popularity (so no `__builtin` functions) and usage frequency (so there almost surely are similar things I don't know about) and are not really sorted in any reasonable order. Let's begin. [cut] <hr> - ### `all(x)` This may be an exception to the rule of non-popularity -- this is quite widely used, but some next items will depend on `all(x)`, so I define it here. So, I talk about ```[c++] #define all(x) (x).begin(), (x).end() ``` Now sorting a vector looks like `sort(all(vec))` instead of `sort(vec.begin(), vec.end())`. However, it's not all about this define. Imagine you nee...
cyclically shift a vector by $k$. If $k = 1$ then one can write a loop of swaps:, natural if you consider a mask as a sort of a boolean vector)., ++] #define all(x) (x).begin(), (x).end() ``` Now sorting a vector looks like `sort(all(vec, , first $n$ numbers into a vector `vec` of size greater than $n$, you can use, , instead of writing a for loop you can call `std::generate`: filling a vector `vec` by random values, - ### Create a set from a vector, Assume that you have, say, a sorted vector, and you want to check if it contains an element, but, But if $k > 1$ then the easiest way to do this manually is probably to create anothervector, fill, However, be careful! If `pts` is a vector of points, then it's really better to read it in the, If we talk about binary search: assume you have a vector and a predicate `p(x)` so that `p(x, Not many of us know, but if you want to create a `std::set` from a vector and find out that set, Now sorting a vector looks like `sort(all(vec))` instead of `sort(vec.begin(), vec.end())`., `) and returns `vec.begin() + 5`. Usually, to make a vector containing only its unique elements, one, ```[c++] bool has(const vector& vec, int key) { int l = 0, r = vec.size(); while (r, ```[c++] int n = nxt(); vector a(n); generate(all(a), nxt); ```, ```[c++] int n; vector parent, rank;, ```[c++] vector a(nxt()); generate(all(a), nxt); ```, ```[c++] vector getConvexHull(vector pts) { int min_pos = min_element(all(pts

Full text and comments »

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

13.
By TheOneYouWant, history, 7 years ago, In English
Editorial — Codeforces Round #646 Hello, everyone! It was a delight for us to have you participate in our contest. We hope you enjoyed the problems! Here, we present to you the solutions of the problems. I have also prepared some memes for you to enjoy &mdash; disclaimer: not all of them were created by me. [tutorial:1363A] Author of this problem was [user:Ashishgup,2020-05-31]. <spoiler summary="Relevant Meme"> ![ ](/predownloaded/cd/f1/cdf13618b93c6243dec10ec495181286a2616caa.jpg) </spoiler> <spoiler summary="Code for A"> ~~~~~ #include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n, x; int a[N], f[2]; int32_t main() { IOS; int t; cin >> t; while(t--) { f[0] = f[1] = 0; cin >> n >> x; for(int i = 1; i <= n; i++) { cin >> a[i]; f[a[i] % 2]++; } bool flag = 0; for(int i = 1; i <= f[1] && i <= x; i ...
#define vint vector, int main(){ int tc; cin >> tc; while(tc--){ int n, k; cin >> n >> k; vector S, int n, cost = 0; int arr[N], b[N], c[N]; vector g[N];, int n, x; int deg[N]; vector g[N];

Full text and comments »

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

14.
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...
internally as extended vector types, meaning that, if need arises, we may directly apply intrinsics to the, interpreted not as a singular data type, but rather as a pack (or "vector") of smaller, 32- or 64-bit, likely find if you look into other people's solutions who work with vector types because... Reasons?, said, I'll be more than happy if someone figures out a valid attack vector on this approach! (or maybe, the total error of the resulting transform. So, assume $A_0,\dots, A_n$ is the DFT-vector, we want to, they were 64-bit, and returns it as another vector of 64-bit integers., ##### GNU vector extensions, **Multiplicativity of relative error in linear transformations**. Let $x'$ be a vector such that, - `__builtin_convertvector(a, type)` converts vector value $a$ of certain type into anothervector, . - [user:magnus.hegdahl,2025-05-13] for introducing GNU vector extensions to me., /onlinedocs/gcc/Vector-Extensions.html)_, 1. [GNU vector extensions](https://gcc.gnu.org/onlinedocs/gcc/Vector -Extensions.html). As always, As I have tried both of them, I ultimately converged on using GNU vector extensions for two main, For added convenience, you can still use `std::vector` with it via `std::vector, Generally, vector extensions work in a surprisingly simple manner, essentially mirroring that of, Note that direct cast from one vector type to another is essentially equivalent to, One possible attack vector here could be to introduce a lot of zeros in the input, as multiplying, Vector extensions are defined for simple types, such as `int`, `double`, etc. Naturally, we can not, vector $x[0]+y[0], \dots, x[3]+y[3]$, all in just one assembly instruction., vector types, and they will mostly behave in the way we expect them to (i.e., doing component-wise

Full text and comments »

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

15.
By tourist, history, 7 years ago, In English
Codeforces Global Round 5 Editorial Enjoy! <spoiler summary="A. Balanced Rating Changes"> [tutorial:1237A] <spoiler summary="Solution by tourist"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; int flag = 1; for (int i = 0; i < n; i++) { int x; cin >> x; if (x % 2 == 0) { cout << x / 2 << '\n'; } else { cout << (x + flag) / 2 << '\n'; flag *= -1; } } return 0; } ~~~~~ </spoiler> </spoiler> <spoiler summary="B. Balanced Tunnel"> [tutorial:1237B] <spoiler summary="Solution by tourist"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> a(n), b(n); for (int i = 0; i < n; i++) { cin >> a[i]; --a[i]; } for (int i = 0; i < n; i++) { cin >> b[i]; --b[i]; } vector<int> pos(n); for (int i = 0; i < n; i++) { pos[b[i...
= psum[fn]; vector exchange = vector(k, need); int start = min(n - k, l); for, id[2 * maxn]; int n, k; ll need; vectorvector>> answer;, () { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector a(n), b(n, int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector a, int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector< vector, vector prepare(char *s) { vector ans; for (int i = 0; i < 2 * n; i += 2, vector ss, tt; char s[maxn], t[maxn]; int n; vector answer; int cnt[5];, vector v(n); for (int i = 0; i < n; i++){ cin >> v[i].first.first >> v[i, void doreverse(vector &v, int l) { reverse(v.begin(), v.begin() + l); for (int j

Full text and comments »

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

16.
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...
bug is that if 40000 or 7 is changed slightly, or if the vector is moved to the middle, then nothing, swapped, or a vector size is changed, etc., the code suddenly becomes 100x slower on certain inputs, The `vector(7)` in one case immediately caught my attention, because it makes an allocation of, int main() { vector<vector> TLE(40000, vector(7));

Full text and comments »

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

17.
By maomao90, 3 years ago, In English
Editorial for Hello 2024 ### [problem:1919a] Author: [user:maomao90,2024-01-02] <spoiler summary="Hint 1"> When does the game end? </spoiler> <spoiler summary="Solution"> Depending on whether the player chooses to exchange wallets with their opponent on step $1$, $1$ coins will be removed from either the opponent's wallet or the player's wallet. This means that if either of the players still has remaining coins, the game will not end as at least one of the choices will still be valid. The only way that the game ends is when both players have $0$ coins. Since each operation decreases the total amount of coins by exactly $1$, the only way for Alice to win the game is if $a + b$ is odd. </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if ((a + b) % 2 == 0) { cout << "Bob\n"; } else { cout << "Alice\n"; } } ...
) { cout << "NO\n"; return 0; } vector v(n, 0); iota(v.begin(), v.end(), 0, ); } int ptr = 3; vector base = {1, 2}; pe[1] = pe[2] = 1; bool iso = 1, bool done[MAXN]; bool solve(vector grp) { int pr = -1, pl = -1; vector lft, int n; int lvl[MAXN + 5]; int pe[MAXN + 5]; vector ch[MAXN + 5];, int n; unsigned long long r[MAXN], hsh[MAXN], totr; string s[MAXN]; vector> ans;, ll query(vector a) { cout << "? 1"; for (int i = 1; i < n; i++) { cout

Full text and comments »

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

18.
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...
prints /usr/include/c++/4.9.2/debug/vector:357:error: attempt to subscript , ~~~~~ int main() { vector v(3); cout << v[7] << endl; } ~~~~~, в этом режиме выдаёт /usr/include/c++/4.9.2/debug/vector:357:error: attempt to subscript

Full text and comments »

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

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

Full text and comments »

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

20.
By tourist, history, 9 years ago, translation, In English
Hello 2018 -- Tutorial Here is the tutorial of Hello 2018. Enjoy! <spoiler summary="Modular Exponentiation"> Problem writer: [user:tourist,2018-01-08] [tutorial:913A] <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int n, m; scanf("%d %d", &n, &m); printf("%d\n", n >= 31 ? m : m % (1 << n)); return 0; } ~~~~~ </spoiler> </spoiler> <spoiler summary="Christmas Spruce"> Problem writer: [user:BudAlNik,2018-01-08] [tutorial:913B] <spoiler summary="C++ solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> p(n), deg(n); for (int i = 1; i < n; i++) { cin >> p[i]; p[i]--; deg[p[i]]++; } vector<int> sons_leaves(n); for (int i = 0; i < n; i++) { if (deg[i] == 0) { sons_leaves[p[i]]++; } } for (int i = 0; i < n; i++) { if (deg[i] > 0 && sons_leaves[i] < 3) { puts("No"); return 0; } } puts...
~~~~~ #include #include #include <vector, () { int n; cin >> n; vector p(n), deg(n); for (int i = 1; i < n; i++) { cin >> p, ); long long t = vector{-1, 0, 1, 3, 2}[c % 5]; long long p5 = 5, ; vector x(n), fracs; for (int i = 0; i < n; i++) { double foo; cin >> foo, > using namespace std; int main() { int n; cin >> n; vector p(n), deg(n); for, const int FULL = 0xff; const vector B = {1, 2, 4, 8, 16, 32, 64, 128}; const int X_TABLE = B, int main() { int n, L; scanf("%d %d", &n, &L); vector c(n); for (int i = 0; i < n, int main() { int n, P, Q; cin >> n >> P >> Q; int p = mul(P, inv(Q)); vector< vector, int main() { int n, T; scanf("%d %d", &n, &T); vector a(n), t(n); for (int i = 0, int main() { int n, T; scanf("%d %d", &n, &T); vector< vector< pair > > at(n + 1, int main() { int n; cin >> n; vector p(n), deg(n); for (int i = 1; i < n; i, int main() { int n; cin >> n; vector x(n), fracs; for (int i = 0; i < n; i, typedef vector poly;

Full text and comments »

Tutorial of Hello 2018
  • Vote: I like it
  • +463
  • Vote: I do not like it

21.
By YouKn0wWho, 4 years ago, In English
[Tutorial] Common Mistakes in Competitive Programming and How to Avoid Them One thing is for sure. You do make mistakes. I also make miskates and that's what makes us human. But what we can surely do is &mdash; to try to minimize the errors that we make throughout our life. I have compiled some of the mistakes that I made in my early Competitive Programming phase. I also mentioned how to avoid them. Also, in most cases, I will give you a chance to find out what the bug is before I reveal the culprit as I tried to make this blog interactive. The codes that I have used in this blog have been written in C++ as it is the most used language for CP. **So, if you are new to CP, stick with me as you might don't wanna repeat the mistakes that I made when I was a beginner.** #### Mistake 1 Check out the following code: <spoiler summary="Code"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int a = 1000'000'000,b = 1000'000'000; long long product = a * b; cout << product << '\n'; return 0; } ~~~~~ </spoiler> The outp...
Just declare a vector only as much as we need., are declaring a vector of size $10^5$. I used to do this mistake a lot in the beginning. How to solve, n; cin >> n; vector a(N, 0); int sum = 0; for (int i = 0; i < n; i, n; cin >> n; vector a(n, 0); int sum = 0; for (int i = 0; i < n; i, the vector., ; // length of the array if (n == 1) { cout << "YES\n"; continue; } vector, ; // length of the array vector a(n); for (int i = 0; i < n; i++) { // taking the array, This is because you are passing the vector `by value` — meaning every time you are calling, int get_size(vector &a) { return (int)a.size(); } int main() { int n = 1000000, int get_size(vector a) { return (int)a.size(); } int main() { int n = 1000000, int main() { long long val= 1e12; vector v({val, val, val}); // now take sum of, int main() { vector v({1.23, 2.05, 3.003}); // now take sum of all elements double, int main() { vector v; cout << (int)v.size() - 1 << '\n';; return 0; } ~~~~~, int main() { vector v; cout << v.size() - 1 << '\n';; return 0; } ~~~~~, int main() { vector v; for (int i = 0; i < v.size() - 1; i++) { // use i < (int)v.size

Full text and comments »

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

22.
By mohmahkho, 7 years ago, In English
N Dimensional Vector (For std::vector Addicts!) Hi! I hope you are doing well. If you are in love(!) with vectors and you use them a lot, you probably know that defining a multidimensional vector is just a pain in the neck! For example if you are trying to define a 3 dimensional vector with `(n, m, k)` as dimensions you have to write it like this : ~~~~~ vector<vector<vector<int>>> a(n, vector<vector<int>>(m, vector<int>(k))); ~~~~~ Then you change your mind and realize that your data will not fit in an `int`. You decide to change it to `long long`. ~~~~~ vector<vector<vector<long long>>> a(n, vector<vector<int>>(m, vector<int>(k))); ~~~~~ [HITS COMPILE BUTTON] Oops! won't compile (G++ really get's mad at you). Go on and change inner vectors as well. ~~~~~ vector<vector<vector<long long>>> a(n, vector<vector<long long>>(m, vector<long long>(k))); ~~~~~ So if you want a 100 dimensional vector of `long long`s, you literally have to say it 100 times to the compiler that you want your data to be `lon...
N Dimensional Vector (For std::vector Addicts!), multidimensional vector is just a pain in the neck! For example if you are trying to define a 3, , int> d(10, 10); d[2][3].push_back(Vec<1, int>(100, 12345)); // now d[2][3][0] is avector with 100, , you probably know that defining a multidimensional vector is just a pain in the neck! For example if, So if you want a 100 dimensional vector of `long long`s, you literally have to say it 100 times to, This is essentially publicly inheriting from `vector<vector<vector< ... vector ... >>>` in which, ~~~~~ template struct Vec : public vector> { static_assert(D, ~~~~~ vector<vector<vector>> a(n, vector<vector>(m, vector(k))); ~~~~~

Full text and comments »

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

23.
By platelet, 3 years ago, In English
CodeTON Round 5 Editorial ### [problem:1842A] <spoiler summary="Tutorial"> Let's view it as when monsters $x$ and $y$ fight, their health changes into $\max(x-y,0)$ and $\max(y-x,0)$ respectively. So any monster with $0$ health is considered dead. Therefore, a player loses when the health of his monsters are all $0$. Notice that $\max(x-y,0)=x-\min(x,y)$ and $\max(y-x,0)=y-\min(x,y)$. Therefore, after each step, the sum of the health of monsters decrease by the same amount for both players. Therefore, we only need to know $\sum a_i$ and $\sum b_i$ to determine who wins. If $\sum a_i > \sum b_i$, Tsondu wins. Else if $\sum a_i < \sum b_i$, Tenzing wins. Else, it is a draw. </spoiler> <spoiler summary="Code"> ~~~~~ #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int T; cin >> T; while (T--) { int n, m, a[50], b[50]; long long sumA = 0, sumB = 0; cin >> n >> m; for (int i = 0; i < n;...
; while (T--) { int n, x, ai; cin >> n >> x; vector pre[3]; for, int n, ans[N]; vector G[N];, int n, k, A, c[M << 1][2], dp[N]; vector> p[N];, int n, k, A, cnt[N], pa[N]; vector> v[N];, vector trim(vector a, int L, int R) { return vector(a.begin() + L, a.end() - R

Full text and comments »

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

24.
By PrinceOfPersia, 12 years ago, In English
Algorithm Gym :: Data structures Today I want to introduce you some very very useful data structures. In this lecture, we are trying to improve your data structures skills, stay with us and click on **read more**. [cut] Important data structures : Trees ----- Trees are one of the most useful data structures.A tree is a connected-acyclic graph.There are too many types of trees, like : rooted trees, weighted trees, directed trees, tries, etc. Partial sum ----------- There are two types of problems solvable by partial sum. 1.Problems which you are asked to answer some queries about the sum of a part of elements (without modify queries). Solution of all of this problems are the same. You just need to know how to solve one of them. Example : You are asked some queries on an array $a_1,a_2,...a,_n$. Each query give you numbers $l$ and $r$ and you should print $a_l + a_{l+1} + ... + a_r$ . Solution : You need to build another array $s_1, s_2, ..., s_n$ which $s_i = a_1 + a_2 + ... + a_i$ ...
(n)$ times (each time the size of the vector will be at least doubled)., We keep tools in a vector (or an array) and when we have a query to merge two boxes, we put all the, ~~~~~ vector s; void split(int x,int y, int id = 1,int l = 0, int r = n){// id is the index

Full text and comments »

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

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

Full text and comments »

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

26.
By FastestFinger, history, 6 years ago, In English
Editorial — Codeforces Round #648 [problem:1365A] <spoiler summary = "Tutorial"> [tutorial : 1365A] </spoiler> <spoiler summary="Code"> <pre><code> #include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 51; int n, m; int a[N][N]; int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n >> m; set< int > r, c; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { cin >> a[i][j]; if(a[i][j] == 1) r.insert(i), c.insert(j); } } int mn = min(n &mdash; r.size(), m &mdash; c.size()); if(mn % 2) cout << "Ashish" << endl; else cout << "Vivek" << endl; } return 0; } </code></pre> </spoiler> This problem was prepared by [user:Ashishgup,2020-06-07] [problem:1365B] <spoiler summary = "Tutorial"> [tutorial : 1365B] </spoiler> <spoiler summary="Code"> <pre><code> #include <bits/stdc++.h> us...
#define ll long long #define vint vector< int >, (tc--){ int n; cin >> n; map< pair < int, int >, int > pairs; vector< int > a(n), b(n, vector< ll > or_value(Q), answer(n);, vector< vint > ask(Q); vint assign_mask(n);

Full text and comments »

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

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

Full text and comments »

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

28.
By Monogon, history, 5 years ago, In English
[Tutorial] Blossom Algorithm for General Matching in O(n^3) I have decided to write a tutorial on a topic not even [user:Um_nik,2021-06-29] knows! ([source](https://codeforces.me/blog/entry/92248)) In this tutorial, I will talk about the blossom algorithm, which solves the problem of **general matching**. In this problem, you are given an undirected graph and you need to select a subset of edges (called matched edges) so that no two edges share a vertex, and the number of matched edges is maximized. More common in competitive programming is bipartite matching, which is the same problem but when the graph is guaranteed to be bipartite. In competitive programming, general matching seems to get a lot of hate for being very challenging to implement. However, the blossom algorithm is quite beautiful, and important in the history of algorithm research. It will help if you are already familiar with bipartite matching. I will discuss the high level ideas of the algorithm, but my main focus will be on the tricky implementation details. So you may...
~~~~~ struct blossom { int n, m; vector mate, ~~~~~ vector lift(vector &vx) { vector A; while, ~~~~~ vector trace(int x) { vector vx; while(true, ~~~~~ void contract(int c, int x, int y, vector &vx, vector, ) { vector vx = trace(x); vector vy = trace(y

Full text and comments »

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

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

Full text and comments »

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

30.
By tourist, 4 years ago, In English
Codeforces Round #844 Editorial [problem:1782A] <spoiler summary="Explanation"> [tutorial:1782A] </spoiler> <spoiler summary="Source"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt--) { int w, d, h; cin >> w >> d >> h; int a, b; cin >> a >> b; int f, g; cin >> f >> g; int ans = b + abs(a - f) + g; ans = min(ans, a + abs(b - g) + f); ans = min(ans, (d - b) + abs(a - f) + (d - g)); ans = min(ans, (w - a) + abs(b - g) + (w - f)); cout << ans + h << '\n'; } return 0; } ~~~~~ </spoiler> [problem:1782B] <spoiler summary="Explanation"> [tutorial:1782B] </spoiler> <spoiler summary="Source 1"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt--) { int n; cin >> n; vector<int> cnt(n + 1); for (int i = 0; i < n; i++) { int a; cin >> a; cnt[a] += 1; } int ans = 0; ...
--) { int n; cin >> n; vector p(n); for (int i = 1; i < n; i++) { cin, ; cin >> s; vector<vector> at(26); for (int i = 0; i < n; i++) { at[(int) (s, ; p /= 10000; vector<vector> C(n + 1, vector(n + 1)); for (int i = 0; i <= n; i, ; vector fib(h * w + 1); fib[0] = 1; fib[1] = 2; for (int i = 2; i <= h * w, class dsu { public: vector p; vector sz; int n;

Full text and comments »

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

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

Full text and comments »

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

32.
By teraqqq, history, 7 months ago, translation, In English
Vector tracing **Note.** This English translation was produced with the help of ChatGPT. This year, BSUIR Open XIV took place, and I was very happy to travel to Minsk and attend the contest itself. But what I liked even more was the problem that I proposed there. Overall, I had not seen this idea before, though it feels simple enough that it may well have appeared in some earlier contest. So if you know where this idea had shown up before, please let me know. **Problem.** (*BSUIR OPEN XIV*) We are given a $100 \times 100$ grid. Some pairs of adjacent cells are separated by walls, and there are also walls along the boundary of the grid. A ray starts from the center of cell $(r,c)$ in direction $(x,y)$. We need to determine in which cell it will be after traveling a distance of $\sqrt{x^2+y^2}$, assuming the ray reflects off walls. Solving the problem ------------------ Let us look at the vector $(x,y)$ and examine the order in which it crosses the vertical and horizontal grid lines. At th...
Vector tracing, symbols, i.e. maps from the set of states to itself. Then we run the vector -tracking algorithm and, Assume that $x \ge y$. This means the vector is “shallow”, so before each crossing of a horizontal, For example, if we start the vector not from the point $(0,0)$ but from an arbitrary point $(\alpha, In general form, the vector-tracking algorithm can be implemented as follows:, Let us look at the vector $(x,y)$ and examine the order in which it crosses the vertical and, Therefore, if the vector starts from an arbitrary point $(\alpha/y, 0)$, then the length of the $k, Thus, to each vector $(x,y)$ we can assign a string $s(x, y)$ containing the sequence of these, vector $(x,y)$ and examine the order in which it crosses the vertical and horizontal grid lines. At

Full text and comments »

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

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

Full text and comments »

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

34.
By pajenegod, 3 years ago, In English
Shallowest Decomposition Tree Hi Codeforces! Today I want to tell you about a really cool and relatively unknown technique that is reminiscent of Centroid decomposition, but at the same time is also completely different. The most common and well known decomposition tree algorithm out there is the centroid decomposition algorithm (running in $O(n \log n)$). It is a standard algorithm that is commonly used to solve tons of different kind of divide and conquer problems on trees. However, it turns out that there exists another closely related decomposition tree algorithm, that is in a sense optimal, and can be implemented to run in $O(n)$ time in around $30$ lines of code. I have chosen to call it the _Shallowest Decomposition Tree_. This blog will be all about the shallowest decomposition tree. Something I want to remark on before we start is that I did not invent this. However, very few people know about it. So I decided to make this blog in order to teach people about this super cool and relatively unknown tec...
of the input variables x_1, ..., x_m as being 0/1 vectors v_1, ..., v_m in a realvector space, // Rooted tree struct arborescence { std::vectorvector> children; int root; };, arborescence centroid_decomposition_tree(std::vectorvector> graph) { int n, arborescence shallowest_decomposition_tree(std::vectorvector> &graph, int root=0, std::vectorvector> decomposition_tree(n); auto centroid_reroot = [&](int u, auto

Full text and comments »

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

35.
By MikeMirzayanov, 3 years ago, In English
Polygon: Warnings for Packages — Incomplete Tests + Statement/Validator Mismatches Hello, Codeforces! If you're developing problems in Polygon, you might like this image to attract attention. <center> <img src="/predownloaded/b4/b6/b4b6e46dd5811c89440ee98bce405e54e3b905c6.png"/> </center> <i>For the new members of the community, I would like to remind you that Polygon (https://polygon.codeforces.com/) is a system developed and maintained by Codeforces for preparing programming problems. It is there that authors and coordinators develop all the problems for the rounds. Moreover, I believe a significant (large?) portion of the problems for other competitions is also developed there: various stages of ICPC, national competitions of different levels, educational problems for various courses, etc. <b>In 2023, more than 50000 problems were prepared in Polygon (only those for which a package was compiled are counted)!</b></i> We often implement such improvements in Polygon that make the process of preparing a problem more reliable. These often include var...
`vector a = inf.readInts(n, -100, 100, "a");` are correct, but `int t = inf.readInt(1, 10'000, read either as `int t = inf.readInt(1, 10'000, "t");` (a single number) or as ` vector a

Full text and comments »

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

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

Full text and comments »

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

37.
By FastestFinger, 6 years ago, In English
Editorial — Codeforces Round #651 [problem:1370A] <spoiler summary = "Tutorial"> [tutorial : 1370A] </spoiler> <spoiler summary="Code"> <pre><code> #include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e5 + 5; int32_t main() { IOS; int t; cin >> t; while(t--) { int n; cin >> n; cout << n / 2 << endl; } return 0; } </code></pre> </spoiler> This problem was prepared by [user:the_hyp0cr1t3,2020-06-20] [problem:1370B] <spoiler summary = "Tutorial"> [tutorial : 1370B] </spoiler> <spoiler summary="Code"> <pre><code> #include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n; int a[N]; int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n; vector< int > even, odd; for(int i = 1; i ...
; 1; } } vector< int > candidate_second; queue< pair< int, int > > q; vector< int, int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n; vector< int > even, pair query(vector< int > nodes){ cout << "? " << nodes.size() << ' '; for(int i, vector< int > adj[N], depth(N), max_depth(N);, vector< int > node_set; find_nodes(root, 0, mid, node_set);, vector< int > nodes; for(int i = 1; i <= n; i++) nodes.push_back(i);, void find_nodes(int i, int par, int req_depth, vector< int > &nodes){ if(depth[i] == req_depth

Full text and comments »

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

38.
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 ...
~~~~~ #include #include <vector> #include, vector children (n); for (int i = 0; i < n; i++) { cin >> children[i]; }

Full text and comments »

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

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

Full text and comments »

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

40.
By FieryPhoenix, 7 years ago, In English
Codeforces Round #638 (Div. 2) Editorial [problem:1348A] <spoiler summary="Tutorial"> [tutorial:1348A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; void solve(){ int N; cin>>N; //note: 1<<X means 2^X //we put largest coin in first pile int sum1=(1<<N), sum2=0; //we put n/2-1 smallest coins in first pile for (int i=1;i<N/2;i++) sum1+=(1<<i); //we put remaining n/2 coins in second pile for (int i=N/2;i<N;i++) sum2+=(1<<i); cout<<sum1-sum2<<endl; } int main(){ int t; cin>>t; while (t--) solve(); } ~~~~~ </spoiler> [problem:1348B] <spoiler summary="Tutorial"> [tutorial:1348B] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; void solve(){ int N,K; cin>>N>>K; set<int>s; for (int i=0;i<N;i++){ int a; cin>>a; s.insert(a); } //if more than K distinct numbers, print -1 if (s.size()>K){ cout<<-1<<endl; return; ...
vector > start[200005]; int ans[200005]; int where[200005]; int N;

Full text and comments »

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

41.
By errorgorn, 5 years ago, In English
Linear Basis (Xor Basis Extended) As part of the graduation requirements for my school, I have to complete a simple research project, so I decided to do something related to data structure and algorithms. I believe I have come out with a data structure that maintains the basis of vectors in $(\mathbb{Z}/m\mathbb{Z})^d$, where $m$ **may not be prime**. Since this was related to competitive programming, I think it is a good idea to share it here. Hopefully, this algorithm is actually novel :P I would like to thank: - [user:icypiggy,2021-12-26] for being my research mentor and tolerating my dumb questions - [user:rama_pang,2021-12-26] and [user:adamant,2021-12-28] for their helpful suggestions and comments Please comment under the blog or message me on codeforces if any parts are unclear or wrong. Also, I hope that some LGMs can help solve the open problems in this blog. # Introduction Maintaining the basis of vectors in $(\mathbb{Z}/2 \mathbb{Z})^d$, also known as the xor basis algorithm is a well-studie...
$\texttt{Add-Vector}$ is called. In 15 to 23 $\texttt{Add-Vector}$ is called twice, let us show that the, \mathbb{Z})^d$, we can check if a vector is representable as a linear combination of vectors in, algorithm we impose an additional constraint over our vectors such that the $i$-thvector we store, lexicographically largest vector. We will now show that the matrix $A$ also maintains the number of representable, some vector in $(\mathbb{Z}/m\mathbb{Z})^d$ is can be represented by some linear combination of, supports $2$ operations. Given a set $S$ that is initially empty, you can add a vector to $S$ or query, $\texttt{Add-Vector}(\frac{m}{A_{i,i}}A_i)$ is called. Trivial by corollary 1. , **GIANT DISCLAIMER:** In this blog, the words "vector'' and "basis'' are used very loosely. The, . Consider the ring $(\mathbb{Z}/6\mathbb{Z})^2$ and the vector $(3~1)$. In the xor basis algorithm, 1. **(SOLVED)** In line 22 of Algorithm 1, $\texttt{Add-Vector }(\frac{m}{A_{i,i}}A_i)$ is called, Corollary 1: Suppose for some vector $W$, $V=W$ at the $i$-th iteration of the for loop. Then there, Lemma 1: Consider the vector $V$ after the $i$-th iteration of the loop at line 5 of Algorithm 1, With such a construction of the basis, we can easily check if a vector is representable using a, int a; vector v(d); while (q--){ cin>>a;, ll q,d,m; vector arr[105];, rep(x,0,d) arr[x]=vector(d,0);, vector largest(){ vector res(d,0); rep(x,0,d) if (arr[x][x]){ ll mul=(m-1-res[x, vector v2=arr[x]; ll mul=m/arr[x][x]; rep(y,0,d) v2[y]=v2[y]*mul%m; add_vector(v2); } } }

Full text and comments »

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

42.
By Monogon, history, 6 years ago, In English
Efficient 3D Convex Hull Tutorial _Warning: The following contains graphic depictions of geometry, precision errors, and degenerate cases. Viewer discretion is advised._ ### Prerequisites I assume the reader is familiar with: - 2D Convex Hulls - 3D Vector Operations (dot and cross products) ### Introduction Recall that in the 2D convex hull problem, you are given a set of 2D points, and you must compute the smallest convex polygon containing all the given points. By convex, we mean that for any two points $A$ and $B$ inside the polygon, the entire line segment $AB$ is also inside the polygon. The problem in 3D is completely analogous. You are given $n$ 3D points, and you must compute the smallest convex polyhedron containing all the given points. Similarly, a polyhedron is convex if for any two points $A$ and $B$ inside the polyhedron, the line segment $AB$ is also inside the polyhedron. In the 2D case, it is more obvious what the output is. We can simply output a circular list of vertices on the ...
edges. vector<vector> dead(n, vector(n, true)); auto add_face = [&](int a, int, were deleted, and we should ignore them vector<vector> conflict(n); auto add_face, () #define vi vector #define pii pair #define rep(i, a, b) for(int i = (a); i < (b); i, - 2D Convex Hulls - 3D Vector Operations (dot and cross products), vector hull3(const vector &p) { int n = sz(p); assert(n >= 3); vector, vector hull3(vector &p) { int n = sz(p); prepare(p); vector f

Full text and comments »

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

43.
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 void apply(vector &sieve, vector &pattern) { size_t N

Full text and comments »

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

44.
By Monogon, history, 6 years ago, In English
[Tutorial] Voronoi Diagram and Delaunay Triangulation in O(n log n) with Fortune's Algorithm What's a Voronoi Diagram? ------------------ Given a set $S$ of $n$ points in the 2D plane, the Voronoi diagram is a partition of the plane into regions. The region associated with a point $p\in S$ contains precisely the points $q$ such that $q$ is closer to $p$ than any other point in $S$. In other words, a point $q$ belongs to the region of its nearest neighbor. <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Euclidean_Voronoi_diagram.svg/1024px-Euclidean_Voronoi_diagram.svg.png" width="300px" height="auto"/> The Voronoi diagram can be represented by the planar graph of boundaries between regions. A vertex in this graph is where three or more segments meet (or a point at infinity), and an edge is a segment connecting two of these vertices. The way the regions were defined, we see that a segment contains the points equidistant to two points in $S$, so it is part of their perpendicular bisector. Similarly, a Voronoi vertex is equidistant to three or more v...
() #define vi vector #define pii pair #define rep(i, a, b) for(int i = (a); i < (b); i, // vector addition, subtraction, scalar multiplication pt operator+(const pt &o) const

Full text and comments »

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

45.
By awoo, history, 7 years ago, translation, In English
Educational Codeforces Round 87 Editorial [problem:1354A] Idea: [user:BledDest,2020-05-18] <spoiler summary="Tutorial"> [tutorial:1354A] </spoiler> <spoiler summary="Solution (pikmike)"> ~~~~~ t = int(input()) for _ in range(t): a, b, c, d = map(int, input().split()) if b >= a: print(b) continue if c <= d: print(-1) continue a -= b dif = c - d print(b + (a + dif - 1) // dif * c) ~~~~~ </spoiler> [problem:1354B] Idea: [user:BledDest,2020-05-18] <spoiler summary="Tutorial"> [tutorial:1354B] </spoiler> <spoiler summary="Solution (BledDest)"> ~~~~~ #include<bits/stdc++.h> using namespace std; char buf[200043]; int main() { int t; scanf("%d", &t); for(int i = 0; i < t; i++) { scanf("%s", buf); string s = buf; int ans = int(1e9); int n = s.size(); vector<pair<char, int> > c; for(auto x : s) { if(c.empty() || c.back().first != x) c.push_back(make_pair(x, 1)); else c.back().second++; } int m = c.size(); for...
<vector> using namespace std;, for (int i = 1; i <= n; i++) { vector min_v(m + 1, INF64); vector, if (n > m) { vector<vector> new_costs(m, vector(n));, int n, m; int a[3]; vector g[N];, int n, q; vector a, k;, int s, t, V; vector g[N]; vector e;, int tot0, tot1; int clr[N]; vector<vector> vts[2]; bool ok;, int64_t score = -hungarian(costs); dbg(score); vector solution;, template int64_t hungarian(vector<vector> costs) { int n = int(costs.size, vector assignment;, vector u(n + 1), v(m + 1); vector p(m + 1), way(m + 1);, vector<vector> costs(N, vector(N, 0));, void run_case() { int N, K; cin >> N >> K; vector A(N), B(N);, void solve() { vector siz; memset(clr, -1, sizeof(clr)); vts[0].clear(); vts[1].clear

Full text and comments »

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

46.
By errorgorn, 5 years ago, In English
[Tutorial] Knapsack, Subset Sum and the (max,+) Convolution **Edit**: I have realized that this blog has been sent quite a lot on discord servers, so I am adding a content page at the start to help organize this blog better. ## Prerequisites Let us first define the classical knapsack, unbounded knapsack and subset sum problems. #### Subset Sum There are $N$ items. The $i$-th item has weight $w_i$. Find a set $S$ such that $\sum\limits_{i \in S} w_i = C$. #### Knapsack There are $N$ items. The $i$-th item has weight $w_i$ and value $v_i$. Find a set $S$ such that $\sum\limits_{i \in S} w_i \leq C$ and $\sum\limits_{i \in S} v_i$ is maximized. #### Unbounded Knapsack There are $N$ items. The $i$-th item has weight $w_i$ and value $v_i$. Find a **multiset** $S$ such that $\sum\limits_{i \in S} w_i \leq C$ and $\sum\limits_{i \in S} v_i$ is maximized. You should know how to do both versions of knapsack in $O(NC)$ and subset sum in $O(\frac{NC}{32})$ before reading this blog. In this blog post, I will just show some res...
```c++ // smawck for max template std::vector smawck(F f, at least as good, it's always at least as good template std::vector smawck(F f, int n, template std::vector MaxConvolutionWithConvexShape(std::vector anyShape, const std

Full text and comments »

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

47.
By DrSwad, history, 7 years ago, In English
A Beautiful Technique for Some XOR Related Problems ## Inspiration I'm very excited about this blog, as it took me quite a lot of effort and scavenging through the internet to completely grasp the concept of this technique(That's probably because I have almost zero knowledge in Linear Algebra or I'm just plain dumb). So I feel like I genuinely conquered a challenge, and I really want to share it with someone. But there's no way my CP friends circle will believe it, they'll think I'm just trying to show off :P So here I am, sharing it on CF. I also created a [personal blog](https://drschwad.github.io/), so that if I ever feel like sharing something again(not only about CP), I can write a blog there. I also added this same post [there](https://drschwad.github.io/2019-08-06-z2-space-xor-trick/), you can read it there if you prefer dark theme. I'll be pleased to hear any thoughts on the blog or if I can improve it in some way ^\_^ ## Introduction Since it concerns Linear Algebra, there needs to be a lot of formal stuff going on ...
$d.$ Suppose at each step, we're taking an input vector $\vec{v_i}$ and we already have a basis, coordinates get added modulo $2,$ which actually gives us the position vector of the xor of these two position, details right below): 1. Represent each given number in it's binary form and consider it as avector in, the size of the basis of a vector space, then the moment you have $d$ independent vectors in a set, ## Part 1: Relating XOR with Vector Addition in $\mathbb{Z}\_2^d$, ## Part 2: Bringing in Vector Basis, $\underline{\text{Basis of a Vector Space:}}$ A set of vectors is called a basis of avector space, $\underline{\text{Vector Space}}$: Just a collection of vectors., . But first, we need to see how we can efficiently find the basis of a vector space of $n$ vectors, 2. Notice that, in case of $\mathbb{Z}\_2^d$ vector space, the coefficients in the linear, 3. The basis is actually the smallest sized set such that all other vectors in thevector space are, 7. For a $d-$dimensional vector space, it's basis can have at most $d$ vector elements., A few important properties of independent vectors and vector basis that we will need later on(I, So, what we've seen is that the xor-operation is equivalent to vector addition in a $\mathbb{Z}\_2, Think of each element as a vector of dimension $d = 20.$ Then the vector space is $\mathbb{Z}\_2, if (!basis[i]) { // If there is no basis vector with the i'th bit set, then insert thisvector into, int q; ii q_data[N]; vector q_at[N]; int powers[N]; int ans[N];, mask ^= basis[i]; // Otherwise subtract the basis vector from this vector } } ~~~~~, ~~~~~ int basis[d]; // basis[i] keeps the mask of the vector whose f value is i

Full text and comments »

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

48.
By DeadlyCritic, history, 6 years ago, In English
Codeforces Round #652 (Div. 2) Editorial ####[A. FashionabLee :](https://codeforces.me/contest/1369/problem/A) Invented by [user:DeadlyCritic,2020-06-16]. <spoiler summary="Brief Solution"> $\mathcal Brief\;\mathcal Solution :$ A $n$-regular convex polygon is beautiful if and only if $n \% 4 = 0$. ($\%$ is the modular arithmetic symbol) </spoiler> <spoiler summary="Complete Proof"> [tutorial:1369A] </spoiler> <spoiler summary="Python solution"> ~~~~~ t = int(input()) for testcase in range(t): n = int(input()) if(n%4 == 0) : print("Yes") else : print("No") ~~~~~ </spoiler> <spoiler summary="C++ solution"> ~~~~~ #include <iostream> using namespace std; int main(){ int t; cin >> t; while(t--){ int n; cin >> n; if(n % 4 == 0){ cout << "YES\n"; } else cout << "NO\n"; } } ~~~~~ </spoiler> ####[B. AccurateLee :](https://codeforces.me/contest/1369/problem/B) Invente...
priority_queuevector, greater> pq;, vector v[MN], a; vector f;, vector v[MN];

Full text and comments »

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

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

Full text and comments »

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

50.
By adamant, history, 5 years ago, In English
Theoretical grounds of lambda optimization Hi everyone! This time I'd like to write about what's widely known as "Aliens trick" (as it got popularized after 2016 IOI problem called [Aliens](https://ioinformatics.org/files/ioi2016problem6.pdf)). There are already some articles about it here and there, and I'd like to summarize them, while also adding insights into the connection between this trick and generic Lagrange multipliers and Lagrangian duality which often occurs in e.g. linear programming problems. Familiarity with a [previous blog](https://codeforces.me/blog/entry/98524) about ternary search or, at the very least, definitions and propositions from it is expected. Great thanks to [user:mango_lassi,2022-01-01] and [user:300iq,2022-01-01] for useful discussions and some key insights on this. Note that although explanation here might be quite verbose and hard to comprehend at first, the algorithm itself is stunningly simple. Another point that I'd like to highlight for those already familiar with "Aliens tr...
const int inf = 1e9; const int maxn = 35001; const int maxs = 4 * maxn; int a[maxn];vector, vector max_conv(vector a, vector b) { vector c = {a[0] + b[0]}; merge, ~~~~~ // a and b are convex, compute c[i+j] = min(a[i] + b[j]) vector min_conv( vector a

Full text and comments »

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

51.
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...
vector tot(N + 1); tot[N] = 1; vector<vector> dp(N + 1, vector(N + 1, vector<vector> banned(N, vector(N)); for (int i = 0; i < K; ++i) { int x, vector<vector> dp(n + 1, vector(n + 1, 0));, vector<vector> ssum(N + 2, vector(N + 1));

Full text and comments »

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

52.
By -is-this-fft-, history, 2 years ago, In English
PSA on Meta Hacker Cup (must read if its your first time!) Meta Hacker Cup is upon us again. Along with it comes the unique format where we have to run our code on large test cases ourselves. Unfortunately, past experience shows that not everyone knows how to do this reliably. Usually, after the first round, many people lose points as a result of an unreliable workflow. This time, let's try to prevent that from happening. Sorry for the somewhat self-important title, but I really do wish that everyone understood this and that no one will fail the contest because of this. ### Don't EVER copy-paste huge files A lot of people's workflow to run a solution is the following: - Click some green button in the IDE - A box comes up, copy-paste the input into that box - The output shows up somewhere This may work well for running your solution on small sample test cases. It is **terrible** for running your solution on the huge test cases in Meta Hacker Cup. In last year's Round 1, the full test case for [problem C](https://www.facebook.com...
``` #include #include <vector>, vector ch [N]; int depth [N];

Full text and comments »

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

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

Full text and comments »

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

54.
By physics0523, history, 4 years ago, In English
Strange Comparison: vector&lt;vector&lt;int&gt;&gt; vs vector&lt;pair&lt;int,int&gt;&gt; ? If we want to use a 2D dynamic array, some C++ user writes following 2D vector: ``` vector<vector<int>> a(n); // add y to a[x] a[x].push_back(y); // walkthrough a[x] for(auto &nx : a[x]){ cout << nx << "\n"; } ``` But we can do the equivalent thing with handwritten linked list (when we know the total size) by using 1D vector<pair<int,int>>: ``` pair<int,int> empty={-1,-1}; vector<pair<int,int>> b(n+total_size,empty); int add_point=n; // add y to b[x] if(b[x]!=empty){ b[add_point]=b[x]; b[x].second=add_point; add_point++; } b[x].first=y; // walkthrough b[x] int current=x; while(current!=empty.second && b[currnt]!=empty){ cout << b[current].first << "\n"; current=b[current].second; } ``` So, what's the benefit for the later implementation? The merit is the generation time of later one is very fast. vector size = $10^5$, Total elements = $10^6$ (this means we need `vector<vector<int>>(1e5)` and the sum of the size of $10^5$ vect...
Strange Comparison: vector<vector<int>> vs vector<pair<int,int>> ?, using 1D vector>:, If we want to use a 2D dynamic array, some C++ user writes following 2D vector:, So, when the vector size is large and need small number of walkthrough, the ` vector, ``` pair empty={-1,-1}; vector> b(n+total_size,empty); int add_point=n;, ``` vector<vector> a(n);, vector size = $10^5$, Total elements = $10^6$ (this means we need `vector<vector >(1e5)` and, vector size = $10^6$, Total elements = $10^6$, vector size = $10^6$, Total elements = $10^7$, | | generate | walkthrough | | ---- | ---- | ---- | vector<vector<int>>

Full text and comments »

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

55.
By Radewoosh, 8 years ago, In English
Blogewoosh #3 Hello, codeforces! This time I've decided to choose a task from my own contest which took place last April and was known as the Grand Prix of Poland. If you want to write this contest virtually in the future, then consider not reading this blog. If you've participated in this contest and maybe even solved this task, then anyway I recommend reading it, cause this task has many very different solutions, each of them being very interesting (in my opinion). It's also a reason why this blog is longer than previous ones. I'll write about task C "cutting tree" (not uploaded to the ejudge yet :/). The statement goes as follows: You are given a tree with $n$ vertices ($1 \leq n \leq 2 \cdot 10^5$). The task is to calculate $f(k)$ for each integer $k$ from the range $[1, n]$ where $f(k)$ is defined as the maximum number of connected components of size $k$ which we can "cut off" from the tree. A connected component of size $k$ is a set of $k$ vertices such that it's possible to traverse ...
vector which for each $i$ denotes the lowest vertex with size at least $i$. In previous solution we

Full text and comments »

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

56.
By Anadi, history, 6 years ago, In English
Good Bye 2020 Editorial [problem:1466A] - Author: [user:Okrut,2020-12-30] - Developer: [user:Anadi,2020-12-30] - First solve: [user:Mip182,2020-12-30] <spoiler summary="Tutorial"> [tutorial:1466A] </spoiler> <spoiler summary="Solution 1"> ``` #include <bits/stdc++.h> using namespace std; void solve() { int n; scanf("%d", &n); vector <int> in(n); vector <int> is(N); for(auto &p: in) scanf("%d", &p); for(int i = 0; i < n; ++i) for(int j = i + 1; j < n; ++j) is[in[j] - in[i]] = true; int ans = 0; for(auto &v: is) ans += v; printf("%d\n", ans); } int main() { int cases; scanf("%d", &cases); while(cases--) solve(); return 0; } ``` </spoiler> <spoiler summary="Solution 2"> ``` #include <bits/stdc++.h> using namespace std; void solve() { int n; scanf("%d", &n); vector <int> in(n); for(auto &p: in) scanf("%d", &p); set <int> S; for(int i = 0; i < n; ++i) for(int j = i + 1; j < n; ++j) S.insert(in[j...
/* Get all borders based on dp from kmp */ vector get(vector &dp, int m) { vector, LL ans = 0; vector to_sort;, int n, q; string s, t; vector songs;, int n; vector cycles; map dp;, state(vector _lengths) { lengths = _lengths; }, vector in(n); vector is(N);, vector kmp(string &in) { int m = in.size(), cpref = 0; vector dp(m, 0);, vector nxt; string ans = S.top().nd;, vector pw; vector sum[26];, vector vis(n); vector cycle_lengths;

Full text and comments »

Tutorial of Good Bye 2020
  • Vote: I like it
  • +316
  • Vote: I do not like it

57.
By Um_nik, 8 years ago, In English
How to read problem statements But [user:Um_nik,2018-10-26], we all know how to read, we have our whooping 2 month of experience! Oh, my sweet summer child, my experiments show that many people with kinda cool achievements like medals on ROI don't know how to read statements. But don't worry, I'll teach you. Well, probably you won't understand anything, because you didn't try to understand anything in your life, you expect all hard work to be done for you by someone else. Let's start! Basic rules ================== - The result of reading the statement is usually pure math model. If story helps to build correct understanding, you can keep it, but still try to discard as many unnecessary details as possible. - Imagine you want to tell the problem to someone else. What parts you want to tell? (According to my PM, this rule won't help you). - Shorter = better. - Simpler = better. - Limitations are part of problem statement. Especially small limitations, because for small data you can try all the possib...
divisible by $Q$; $y$ has all coordinates divisible by $Q$. Or, in other words, we take non-zerovector, vector with some non-integer coordinates which after multiplying with the matrix becomes all-integer

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

61.
By ninja_28, history, 6 years ago, In English
CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial [problem:1498A] ================== #### [**Video Editorial**](https://www.youtube.com/watch?v=lV5cb8wh3sE) **Author and Problemsetting:** [user:ninja_28,2021-03-29] **Editorialist:** [user:sigma_g,2021-03-29] <spoiler summary="Hint"> Can you think of the simplest properties that relate a number and its sum of digits? </spoiler> <spoiler summary="Hint 2"> Note that if $X$ is a multiple of 3, then **both** $X$ as well as the sum of digits of $X$ are a multiple of 3! Can you put this property to use here? </spoiler> <spoiler summary="Hint 3"> If $X$ is a multiple of 3, then $\texttt{gcd-sum}(X) \ge 3$. Therefore, we are guaranteed that at least every third number will satisfy the constraints required by our problem $(\texttt{gcd-sum}(X) > 1)$. </spoiler> <spoiler summary="Solution"> Therefore, for the input $n$, we can simply check which one of $n$, $n+1$, and $n+2$ has its gcd-sum $> 1$, and print the lowest of them. </spoiler> <spoi...
using VI = vector; using VVI = vector<vector>;, vector is_seen(M + 1, false); is_seen[0] = true; vector answer(M + 1, -1

Full text and comments »

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

62.
By Keshi, 4 years ago, In English
Codeforces Round #800 Editorial ###[problem:1694A] Idea: [user:AmShZ,2022-06-16] <spoiler summary="Solution"> [tutorial:1694A] </spoiler> <spoiler summary="Implementation"> ~~~~~ # include <bits/stdc++.h> using namespace std; int t, A, B; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> t; while (t --){ cin >> A >> B; for (int i = 0; i < min(A, B); ++ i) cout << "01"; for (int i = 0; i < abs(A - B); ++ i) cout << (A < B ? 1 : 0); cout << '\n'; } return 0; } ~~~~~ </spoiler> ###[problem:1694B] Idea: [user:AmShZ,2022-06-16] <spoiler summary="Solution"> [tutorial:1694B] </spoiler> <spoiler summary="Implementation"> ~~~~~ # include <bits/stdc++.h> using namespace std; int t, n; string S; long long ans; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> t; while (t --){ cin >> n >> S, ans = n; for (int i = 1; i < n; ++ i) if (S[i] != S[i - 1]) ans += i; cout << ans << '\n'; ...
int n, a[N], min_r[N], fen[N]; long long ans; stack sk; vector vec[2][N];, int n, m, d[N], dist[N]; priority_queue > pq; vector adj[N]; bool mark[N];, int t, n, l[N], r[N], ans; vector adj[N];

Full text and comments »

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

63.
By Vladithur, history, 4 years ago, In English
Codeforces Round #813 (Div. 2) Editorial Thanks for participating in the round, we hope you liked the problems! <spoiler summary="Solve count predictions (official div. 2)"> Handle | A | B | C | D | E1 | E2 | F --- | --- | --- | --- | --- | --- | --- | --- [user:Vladithur,2022-08-13] | 16K | 8K | 3K | 900 | 500 | 50 | 4 [user:_dlbm17,2022-08-13] | 14K | 9K | 5K | 500 | ? | ? | ? [user:thanhchauns2,2022-08-13] | 14K | 8K | 2K | 1K | 500 | ? | ? [user:QuangBuiCP,2022-08-13] | 14K | 7K | 2K | 1K | 500 | 24 | 5 [user:welleyth,2022-08-13] | 16K | 10K | 4K | 1.5K | 600 | 130 | 2 [user:Kon567889,2022-08-13] | 14K | 10K | 5K | 2K | ? | ? | 5 </spoiler> [problem:1712A] <spoiler summary="Hint"> The smallest possible sum is $1 + 2 + \ldots + k$. </spoiler> <spoiler summary="Tutorial"> [tutorial:1712A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const ch...
vector a(n); mapvector> p; for (int i = 0; i < n; i++) { cin >> a[i, vector ans(T); vector> queries;, vector ans, x;, vector<vector> d(2*maxn + 1);, vector<vector>> segs(maxn + 1);

Full text and comments »

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

64.
By maomao90, history, 3 years ago, In English
Breaking the 100 point barrier for IOI 2010 Maze After 21 days and 56 submissions on [IOI 2010 Maze](https://oj.uz/problem/view/IOI10_maze?locale=en), I finally broke the 100 point barrier and achieved a score of 100.081 / 100. ![Score distribution](/predownloaded/3a/0a/3a0a7cf4905b5c66c3eac59c02f5215bdd9365e8.png) [cut] ![Page 3 of submissions](/predownloaded/a4/7e/a47e4cf96e4646b18bf9faaa26b0fd231a594c0f.png) ![Page 2 of submissions](/predownloaded/55/2f/552fe37390378626f2b2171a9e42bd61d6a5fc7b.png) ![Page 1 of submissions](/predownloaded/5a/82/5a82cb9bb180f3951dbeee7349507c983063de1a.png) # Methodology It's just simulated annealing + a lot a lot of time. The neighbour function to generate a new state was just randomly choosing one cell to change from '$\text{#}$' to '$\text{.}$' or from '$\text{.}$' to '$\text{#}$'. Remember to take care that there must be exactly one '$\text{.}$' at the edge of the maze at all times. The energy function that we are optimizing is the question itself, which is the maxim...
) x.size() #define pb push_back typedef vector vi; typedef vector vll; typedef vector vii

Full text and comments »

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

65.
By awoo, history, 6 years ago, translation, In English
Educational Codeforces Round 95 Editorial [problem:1418A] Idea: [user:vovuh,2020-09-15] <spoiler summary="Tutorial"> [tutorial:1418A] </spoiler> <spoiler summary="Solution (vovuh)"> ~~~~~ for i in range(int(input())): x, y, k = map(int, input().split()) print(((y + 1) * k - 1 + x - 2) // (x - 1) + k) ~~~~~ </spoiler> [problem:1418B] Idea: [user:BledDest,2020-09-15] <spoiler summary="Tutorial"> [tutorial:1418B] </spoiler> <spoiler summary="Solution (Ne0n25)"> ~~~~~ #include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) #define forn(i, n) for (int i = 0; i < int(n); ++i) void solve() { int n; cin >> n; vector<int> a(n), b(n), c; forn(i, n) cin >> a[i]; forn(i, n) cin >> b[i]; forn(i, n) if (!b[i]) c.push_back(a[i]); sort(c.rbegin(), c.rend()); int j = 0; forn(i, n) { if (b[i]) cout << a[i] << ' '; else cout << c[j++] << ' '; } cout << '\n'; } int main() { int T; ...
vector a; vector> t; vector ps;, vector< vector > ans(n + 1);

Full text and comments »

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

66.
By sammyuri, 6 months ago, In English
Spectral::Cup 2026 Round 2 (Codeforces Round 1100, Div. 1 + Div. 2) Editorial Thank you for participating in our round! We hope you enjoyed the problems as much as we enjoyed preparing them. <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Absolute Cinema contest - Excellent contest - Good contest - Average contest - Bad contest - Horrible contest </spoiler> <spoiler summary="Difficulty"> - Trivial contest - Easy contest - Average contest - Hard contest - Impossible contest </spoiler> </spoiler> [problem:2229A] Idea by: [user:Intellegent,2026-05-23] Prepared by: [user:Intellegent,2026-05-23] Editorial by: [user:reirugan,2026-05-23] <spoiler summary="Hint 1"> Let $y$ denote the final position of all of the slimes. Then it is optimal to choose $x = y$ for every operation. </spoiler> <spoiler summary="Hint 2"> Let $\mathrm{mn}$ denote the minimum value in $a$, a...
mint ans = 0; vector<vector> dp(n + 1, vector(n + 1)); dp[0][n] = 1;, using ll = long long; using vi = vector; using vl = vector; using pl = pair, vector h; vector pref;, vector<vector> g(n); for (int i = 0; i < n - 1; i++){ int u, v; cin

Full text and comments »

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

67.
By Sulfox, 7 years ago, In English
Codeforces Round #635 Editorial [problem:1337A] Idea: [user:Sooke,2020-04-16] <spoiler summary="Tutorial"> [tutorial:1337A] </spoiler> <spoiler summary="Solution by Sooke"> ~~~~~ #include <bits/stdc++.h> using namespace std; int t, a, b, c, d; int main() { for (cin >> t; t; t--) { cin >> a >> b >> c >> d; cout << b << " " << c << " " << c << endl; } return 0; } ~~~~~ </spoiler> [problem:1337B] Idea: [user:EternalAlexander,2020-04-16] <spoiler summary="Tutorial"> [tutorial:1337B] </spoiler> <spoiler summary="Solution by EternalAlexander"> ~~~~~ #include <bits/stdc++.h> int x,n,m,t; void solve(){ scanf("%d%d%d",&x,&n,&m); while (x>0&&n&&x/2+10<x){n--;x=x/2+10;} if (x<=m*10)printf("YES\n"); else printf("NO\n"); } int main(){ scanf("%d",&t); while(t--)solve(); return 0; } ~~~~~ </spoiler> [problem:1336A] Idea: [user:EternalAlexander,2020-04-16] <spoiler summary="Tutorial"> [tutorial:1336A] </spoiler> <spoiler...
vector<vector > f(n + 1, vector(m + 1));

Full text and comments »

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

68.
By Monogon, history, 5 years ago, In English
[Tutorial] Graph Potentials, Johnson's Algorithm, and Min Cost Max Flow In this tutorial I'll introduce potentials as it applies to directed graphs and discuss a few of its applications. I haven't seen many resources about this topic, so I decided to write one. Prerequisites: - Shortest path algorithms ([Dijkstra](https://cp-algorithms.com/graph/dijkstra.html) and [Bellman-Ford](https://cp-algorithms.com/graph/bellman_ford.html)) - For the Min Cost Max Flow section, you should be familiar with [Ford-Fulkerson](https://cp-algorithms.com/graph/edmonds_karp.html). But you can benefit from this blog with just the Johnson's Algorithm section if you're not familiar with flows. Introduction ------------------ For notation, let's say there is a weighted, directed graph $G=(V,E)$. Let $n=|V|$ and $m=|E|$. For simplicity, let's assume there are no loops or multiple edges between the same pair of nodes in the same direction. For an edge $u\to v$, we will use $w(u\to v)$ to denote its weight. Let's motivate the idea of a potential, so the definition d...
; Cap cap, flow; Cost cost; }; int n; vector e; vector<vector

Full text and comments »

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

69.
By Artyom123, 5 years ago, translation, In English
Codeforces Global Round 16 Editorial We hope that you enjoyed the contest. Let's get right into the editorial: <spoiler summary="A: Median Maximization"> [problem:1566A] <spoiler summary="First solution"> <spoiler summary="Hint 1"> Which numbers smaller than the median should be taken? </spoiler> <spoiler summary="Hint 2"> Which numbers bigger than the median should be taken? </spoiler> <spoiler summary="Hint 3"> Greedy algorithm. </spoiler> <spoiler summary="Editorial"> Let's consider the array of $n$ elements in non-decreasing order. We can make numbers before the median equal to zero, after that we have $m = \lfloor {\frac{n}{2}} \rfloor + 1$ numbers, which sum should be $n$ and the minimal of them (i.e. median value) should be maximized. To do so, it is enough to make all these numbers equal $\lfloor {\frac{s}{m}} \rfloor$, and then add what's left to the last number ($s \bmod m$). It's easy to see that such array matches all the conditions and it is impossible to make median greater. </s...
vector<vector> g; vector type; // -1 -- default, 0 -- root, 1 -- leaf, 2 -- bud

Full text and comments »

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

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

Full text and comments »

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

71.
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...
An alternative solution is to use `vector b(1000000001)` because it's memory-optimized too

Full text and comments »

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

72.
By tourist, 4 years ago, translation, In English
Codeforces Round #850 Editorial [problem:1786A2] Problem author: [user:KAN,2023-02-15] <spoiler summary="Explanation"> [tutorial:1786A2] </spoiler> <spoiler summary="Code by KAN"> ~~~~~ NT = int(input()) for T in range(NT): n = int(input()) answer = [0, 0, 0, 0] first_card = 1 for it in range(1, 20000): who = 0 if it % 4 == 1 or it % 4 == 0 else 1 cnt = it if n < cnt: cnt = n cnt_white = (cnt + first_card % 2) // 2 cnt_black = cnt - cnt_white answer[who * 2 + 0] += cnt_white answer[who * 2 + 1] += cnt_black first_card += cnt n -= cnt if n == 0: break assert(n == 0) print(*answer) ~~~~~ </spoiler> [problem:1786B] Problem author: [user:KAN,2023-02-15] <spoiler summary="Explanation"> [tutorial:1786B] </spoiler> <spoiler summary="Code by KAN"> ~~~~~ #include <bits/stdc++.h> using namespace std; const int inf = 1000000000; int main() { int tt; cin >> tt; while (tt--) { int n, w, h; cin >> n >> w >> h; ...
vector fact(1, 1); vector inv_fact(1, 1);

Full text and comments »

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

73.
By SanguineChameleon, 19 months ago, In English
Neowise Labs Contest 1 (Codeforces Round 1018, Div. 1 + Div. 2) Editorial [Sorry about problem H.](https://codeforces.me/blog/entry/142069) Thank you for understanding, and we hope you enjoyed the rest of the problems :D --- <h3>[problem:2096A]</h3> Idea: [user:SanguineChameleon,2025-04-20] <br> <spoiler summary="Step 1"> Create your own test cases and solve them! What can you observe? </spoiler> <spoiler summary="Step 2"> What is the length of the $n$-th stick? <spoiler summary="Answer"> - If $s_{n - 1} = \texttt{<}$, then $a_n = 1$, because the $n$-th stick must be shorter than all the other sticks. - If $s_{n - 1} = \texttt{>}$, then $a_n = n$, because the $n$-th stick must be longer than all the other sticks. </spoiler> </spoiler> <spoiler summary="Step 3"> Can we do something similar for the remaining sticks? <spoiler summary="Answer"> Yes! Remove the $n$-th stick, and then solve for the remaining $n - 1$ sticks. We can make similar observations about the $(n - 1)$-th stick. Then, remove the $(n - 1)$-th st...
long long solveHor(int n, vector<vector>& h, vector& a) { vector<vector

Full text and comments »

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

74.
By awoo, history, 6 years ago, translation, In English
Educational Codeforces Round 91 Editorial [problem:1380A] Idea: [user:BledDest,2020-07-12] <spoiler summary="Tutorial"> [tutorial:1380A] </spoiler> <spoiler summary="Solution (Ne0n25)"> ~~~~~ #include <bits/stdc++.h> using namespace std; const int N = 1000; int n; int a[N]; void solve() { cin >> n; for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 1; i < n - 1; ++i) { if (a[i] > a[i - 1] && a[i] > a[i + 1]) { cout << "YES" << endl; cout << i << ' ' << i + 1 << ' ' << i + 2 << endl; return; } } cout << "NO" << endl; } int main() { int T; cin >> T; while (T--) solve(); } ~~~~~ </spoiler> [problem:1380B] Idea: [user:adedalic,2020-07-12] <spoiler summary="Tutorial"> [tutorial:1380B] </spoiler> <spoiler summary="Solution (adedalic)"> ~~~~~ fun main() { val winBy = mapOf('R' to 'P', 'S' to 'R', 'P' to 'S') repeat(readLine()!!.toInt()) { val s = readLine()!! val maxCnt = s.groupingBy { it }.eachCount().maxBy ...
int n, m; vector p; vector<vector> val; vector who;

Full text and comments »

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

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

Full text and comments »

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

76.
By arujbansal, 5 years ago, In English
[Tutorial] 2-SAT Introduction ================== In computer science, 2-satisfiability, 2-SAT or just 2SAT is a computational problem of assigning values to variables, each of which has two possible values, in order to satisfy a system of constraints on pairs of variables. It is a special case of the general Boolean satisfiability problem, which can involve constraints on more than two variables, and of constraint satisfaction problems, which can allow more than two choices for the value of each variable. But in contrast to those more general problems, which are NP-complete, 2-satisfiability can be solved in polynomial time. -[Wikipedia](https://en.wikipedia.org/wiki/2-satisfiability) If you have not heard of propositional logic before, plead read about it [here](https://brilliant.org/wiki/propositional-logic/). Wikipedia links have been provided wherever a term has been used for the first time in this tutorial. The whole algorithm is based on graph theory so it will help to be familiar with direc...
struct two_sat { int n; vector<vector> g, gr; vector comp

Full text and comments »

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

77.
By wlzhouzhuan, history, 5 years ago, In English
I don't think the interactor of CF1557E is smart enough. Hello, codeforces! I don't think the interactor of [CF1557E](https://codeforces.me/contest/1557/problem/E) is smart enough. Many wrong codes can get Accepted. First, the hack input format in CF1557E is: ``` T x[1] y[1] x[2] y[2] ... x[T] y[T] ``` As you see, we can only input the coordinate of the King, but the King's route is by interactor. So I have no way to hack it, but to post a blog to say it. Take my code as an example: https://codeforces.me/contest/1557/submission/125431623 . It's not correct, and it can be easily hacked. Here is my `Hand Player` , which you can control the King's route (use Windows) : ``` // Author: wlzhouzhuan #include <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pii pair<int, int> #define pb push_back #define fir first #define sec second #define rep(i, l, r) for (int i = l; i <= r; i++) #define per(i, l, r) for (int i = l; i >= r; i--) #define mset(s, t) memset(...
vector vec; bool ban[10][10]; int Qx, Qy; int Kx, Ky;

Full text and comments »

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

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

Full text and comments »

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

79.
By awoo, history, 4 years ago, In English
Educational Codeforces Round 143 Editorial [problem:1795A] Idea: [user:BledDest,2023-02-17] <spoiler summary="Tutorial"> [tutorial:1795A] </spoiler> <spoiler summary="Solution (Neon) 1"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { auto ok = [](string s) { for (int i = 1; i < (int)s.size(); ++i) if (s[i - 1] == s[i]) return false; return true; }; int t; cin >> t; while (t--) { int n, m; string s, t; cin >> n >> m >> s >> t; bool f = false; for (int x = 0; x < 2; ++x) { string cs = s, ct = t; for (int i = 0; i < n; ++i) { f |= ok(cs) && ok(ct); ct.push_back(cs.back()); cs.pop_back(); } swap(n, m); swap(s, t); } cout << (f ? "YES\n" : "NO\n"); } } ~~~~~ </spoiler> <spoiler summary="Solution (Neon) 2"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m; string ...
vector<vector> g; vector req; vector used;

Full text and comments »

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

80.
By YouKn0wWho, 5 years ago, In English
Editorial of Codeforces Round #752 Thanks for participating in my contest <a href="https://emoji.gg/emoji/8771_blobheart"><img src="https://emoji.gg/assets/emoji/8771_blobheart.png" width="16px" height="16px" alt="blobheart"></a>. I hope you liked the problems. I would love to hear your feedback in the comments. If you find anything wrong in the editorial which is more likely to happen because I have written a rather long editorial to make you understand the solutions better, then comment below. Also, don't forget to upvote to pay for the editorial. See you in my next contest! [tutorial:1604A] <spoiler summary="Code"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int ans = 0; for (int i = 1; i <= n; i++) { int k; cin >> k; ans = max(ans, k - i); } cout << ans << '\n'; } return 0; } ~~~~~ </spoiler> [tutorial:1604B] <spoiler summary="Code"> ~~~~~ #include<bits/stdc++.h> ...
--) { int n; cin >> n; vector a(n + 1); bool inc = true; for (int i = 1; i <= n; i

Full text and comments »

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

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

Full text and comments »

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

82.
By null_awe, 2 years ago, In English
Codeforces Global Round 26 Editorial Thank you for participating! We put a lot of effort into this contest. Special thanks to [user:TheScrasse,2024-06-08] for contributing to these problems. <spoiler summary="Rating Predictions"> | Person | A | B | C1 | C2 | D | E | F | G | H | |--------------------------------------------|------|------|------|------|------|------|------|------|------| | [user:null_awe,2024-06-08] | 800 | 1000 | 1200 | 1700 | 2200 | 2400 | 2500 | 2900 | 3400 | | [user:buffering,2024-06-08] | 800 | 1000 | 1300 | 1800 | 2300 | 2400 | 2600 | 3100 | 3500 | | [user:redpanda,2024-06-08] | 800 | 1100 | 1200 | 1800 | | | | | | | [user:thescrasse,2024-06-08] | 800 | 1000 | 1200 | 1600 | 2200 | 2500 | 2500 | 3100 | 3400 | | [user:bronze_coder,2024-06-08] | 800 | 1000 | 1600 | 1800 | 2400 | | | 2700 | 3500 | | [user:awesomeguy856,20...
vector<vector> dp; vector<vector> from; vector miss;

Full text and comments »

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

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

Full text and comments »

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

84.
By errorgorn, 19 months ago, In English
1/phi Halving in Interactive Tree Problems Thanks to [user:toxicpie9,2025-04-22] for proofreading and emotional support. Recently, I was thinking about JOISC 2025 Space Thief. And there is a part where you need to do divide and conquer on a tree, where you need to split the edges of the tree into two components where the edges are both connected. Basically, we consider an interactive problem on a tree where there is a hidden edge. We are allowed to ask queries of the form $(v,N_v)$ where $v$ is a vertex of the tree and $N_v$ is a set of neighbouring edges of $v$. Then the query returns to us whether the hidden edge is in the subtree of one of $N_v$ when we root the tree at $v$. We maintain a set of edges that the hidden edge can be in. In each query, we try to split the set of edges into two parts and ask a query to separate them. In the worst case, we replace the set of edges by the larger component. Let $R$ be the maximum ratio of the larger component. In [this blog](https://codeforces.me/blog/entry/120446)...
vector v[30];

Full text and comments »

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

85.
By awoo, history, 6 years ago, translation, In English
Educational Codeforces Round 106 Editorial [problem:1499A] Idea: [user:adedalic,2021-03-19] <spoiler summary="Tutorial"> [tutorial:1499A] </spoiler> <spoiler summary="Solution (adedalic)"> ~~~~~ fun main() { repeat(readLine()!!.toInt()) { val (n, k1, k2) = readLine()!!.split(' ').map { it.toInt() } val (w, b) = readLine()!!.split(' ').map { it.toInt() } if (k1 + k2 >= 2 * w && (n - k1) + (n - k2) >= 2 * b) println("YES") else println("NO") } } ~~~~~ </spoiler> [problem:1499B] Idea: [user:BledDest,2021-03-19] <spoiler summary="Tutorial"> [tutorial:1499B] </spoiler> <spoiler summary="Solution (Neon)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; int i = s.find("11"); int j = s.rfind("00"); cout << (i != -1 && j != -1 && i < j ? "NO" : "YES") << endl; } } ~~~~~ </spoiler> [problem:1499C] Idea: [use...
int k; vector<vector> g; vector<vector> dp;

Full text and comments »

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

86.
By errorgorn, 4 years ago, In English
[Tutorial] Theoretically Faster HLD and Centroid Decomposition This blog was going to be translation of $[1]$ (which is in Chinese) but I think I ended up deviating too much from the source material that it would not be appropriate to call this a translation. Anyways, I am honestly amazed by how ahead of its time this paper is. In its abstract, it starts by saying that the state of art for tree path queries is $O(n \log n + q \sqrt n \log n)$, which I honestly can't fathom how one would arrive, then proceeds to claim that it has found an $O((n+q) \log n)$ algorithm. All the more, in 2007. While I was in the process of writing this blog, [user:smax,2022-07-18] sniped me and posted $[9]$. However, we will focus on static trees **only**. Thanks to [user:oolimry,2022-07-18], [user:everule,2022-07-18] and [user:timreizin,2022-07-18] for proofreading. Note to reader: I am expecting the reader to be familiar with what a splay tree and HLD is. You do not really need to know why splay trees are $O(\log n)$ amortised but you should know what the z...
int n,q; vector al[1000005];, int n,q; vector al[2000005];

Full text and comments »

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

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

Full text and comments »

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

88.
By awoo, history, 6 years ago, translation, In English
Educational Codeforces Round 103 Editorial [problem:1476A] Idea: [user:vovuh,2021-01-30] <spoiler summary="Tutorial"> [tutorial:1476A] </spoiler> <spoiler summary="Solution (adedalic)"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { long long n, k; cin >> n >> k; long long cf = (n + k - 1) / k; k *= cf; cout << (k + n - 1) / n << endl; } return 0; } ~~~~~ </spoiler> [problem:1476B] Idea: [user:adedalic,2021-01-30] <spoiler summary="Tutorial"> [tutorial:1476B] </spoiler> <spoiler summary="Solution (adedalic)"> ~~~~~ #include<bits/stdc++.h> using namespace std; typedef long long li; const int INF = int(1e9); int main() { int t; cin >> t; while(t--) { int n, k; cin >> n >> k; vector<int> p(n); for (int i = 0; i < n; i++) cin >> p[i]; li x = 0; li pSum = p[0]; for (int i = 1; i < n; i++) { x = max(x, (100ll * p[i] - k * pS...
vector<vector> g; vector used, ord; bool cyc;

Full text and comments »

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

89.
By Endagorion, 12 years ago, translation, In English
Codeforces Round #283: editorial (with bonuses!) Each problem comes with a challenge &mdash; a bonus task somehow related to the problem; you may tackle at the challenges for fun and practice, also feel free to discuss them at the comments. =) [problem:496A] For every option of removing an element we run through the remaining elements and find the maximal difference between adjacent ones; print the smallest found answer. The solution has complexity $O(n^2)$. It can be noticed that after removing an element the difficulty either stays the same or becomes equal to the difference between the neighbours of the removed element (whatever is larger); thus, the difficulty for every option of removing an element can be found in $O(1)$, for the total complexity of $O(n)$. Any of these solutions (or even less efficient ones) could pass the tests. **Challenge**: suppose we now have to remove exactly $k$ arbitrary elements (but the first and the last elements have to stay in their places). How small the maximal difference between adjacen...
Let us put the values of $cnt$ in the coordinates of a vector, and also append a coordinate which

Full text and comments »

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

90.
By reirugan, 17 months ago, In English
Codeforces Round 1034 (Div. 3) Editorial I hope you all enjoyed the contest! <spoiler summary="Rating Predictions"> | Predictor | A | B | C | D | E | F | G | |------------------------------------|--------|--------|--------|--------|--------|--------|--------| | [user:AksLolCoding,2025-07-01] | 800 | 900 | 1000 | 1500 | 1500 | 1800 | 1700 | | [user:__baozii__,2025-07-01] | 800 | 800 | 1200 | 1500 | 1500 | 1600 | 1900 | | [user:DivinePunishment,2025-07-01] | 800 | 900 | 1100 | 1400 | 1500 | 1600 | 1900 | | [user:Edeeva,2025-07-01] | 800 | 800 | 1000 | 1200 | 1600 | 1800 | 2200 | | [user:efishel,2025-07-01] | 800 | 800 | 1000 | 1200 | 1400 | 1500 | 1900 | | [user:-firefly-,2025-07-01] | 800 | 800 | 900 | 1400 | 1500 | 1700 | 2000 | | [user:hashman,2025-07-01] | 800 | 900 | 1100 | 1600 | 1500 | 1800 | ...
vector comp(1e5+1); vector primes;

Full text and comments »

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

91.
By awoo, history, 2 years ago, translation, In English
Educational Codeforces Round 171 Editorial [problem:2026A] Idea: [user:adedalic,2024-10-29] <spoiler summary="Tutorial"> [tutorial:2026A] </spoiler> <spoiler summary="Solution (adedalic)"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int X, Y, K; cin >> X >> Y >> K; int M = min(X, Y); cout << "0 0 " << M << " " << M << endl; cout << "0 " << M << " " << M << " 0" << endl; } } ~~~~~ </spoiler> [problem:2026B] Idea: [user:BledDest,2024-10-29] <spoiler summary="Tutorial"> [tutorial:2026B] </spoiler> <spoiler summary="Solution (Neon)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<long long> a(n); for (auto& x : a) cin >> x; long long ans = 1e18; auto upd = [&](vector<long long> a) { sort(a.begin(), a.end()); for (int i = 1; i < (int)a.size(); ++i) if (a[i - 1] == a[i...
vector a; vector pa; vector ppa; vector start, vector<vector> g; vector<vector> qs; vector ans; mindeque ks;

Full text and comments »

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

92.
By Mangooste, history, 5 years ago, In English
Global Round 19 Editorial We hope you enjoyed the contest! We recommend you to read all tutorials even if you solve the problem, maybe you will learn something new. [problem:1637A]<br> Idea: [user:__JustMe__,2022-02-12]. <spoiler summary="Hint 1"> What does happen if the array is already sorted? </spoiler> <spoiler summary="Hint 2"> What does happen if there are two indexes $i$ and $j$, such that $i < j$ and $a_i > a_j$? </spoiler> <spoiler summary="Tutorial"> [tutorial:1637A] </spoiler> <spoiler summary="Solution"> ``` #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int n; cin >> n; vector<int> a(n); for (auto& u : a) cin >> u; if (!is_sorted(a.begin(), a.end())) cout << "YES\n"; else cout << "NO\n"; } } ``` </spoiler> [problem:1637B]<br> Idea: [user:__JustMe__,2022-02-12] and [user:Mangooste,2022-02-12]. ...
ll n; vector<vector> gr; vector vec;

Full text and comments »

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

93.
By gepardo, history, 6 years ago, translation, In English
Разбор Codeforces Round #672 (Div. 2) [problem:1420A] <spoiler summary="Подсказка"> Любой массив можно отсортировать не более, чем за $\frac{n(n-1)}2$ операций. Подумайте либо угадайте, в каком случае понадобится ровно $\frac{n(n-1)}2$. </spoiler> <spoiler summary="Разбор"> [tutorial:1420A] </spoiler> <spoiler summary="Код C++ (Wind_Eagle)"> ~~~~~ #include<iostream> using namespace std; int a[1000000+5]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin>>t; while (t--) { int n; cin>>n; for (int i=0; i<n; i++) { cin>>a[i]; } bool can=false; for (int i=1; i<n; i++) { if (a[i]>=a[i-1]) { can=true; break; } } if (can) cout<<"YES"<<'\n'; else cout<<"NO"<<'\n'; } } ~~~~~ </spoiler> [problem:1420B] <spoiler summary="Подсказка"> Придумайте про...
~~~~~ #include #include <vector>

Full text and comments »

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

94.
By awoo, history, 6 years ago, translation, In English
Educational Codeforces Round 98 Editorial [problem:1452A] Idea: [user:BledDest,2020-11-20] <spoiler summary="Tutorial"> [tutorial:1452A] </spoiler> <spoiler summary="Solution (BledDest)"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { int x, y; cin >> x >> y; int ans = max(x, y) * 2 - 1; if(x == y) ans++; cout << ans << endl; } } ~~~~~ </spoiler> [problem:1452B] Idea: [user:adedalic,2020-11-20] <spoiler summary="Tutorial"> [tutorial:1452B] </spoiler> <spoiler summary="Solution (adedalic)"> ~~~~~ fun main() { repeat(readLine()!!.toInt()) { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toLong() } val k = maxOf(a.max()!!, (a.sum() + n - 2) / (n - 1)) println(k * (n - 1) - a.sum()) } } ~~~~~ </spoiler> [problem:1452C] Idea: [user:BledDest,2020-11-20] <spoiler summary="T...
vector h, pcd, d; vector<vector> st, vals; vector a;

Full text and comments »

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

95.
By awoo, history, 6 years ago, translation, In English
Educational Codeforces Round 102 Editorial [problem:1473A] Idea: [user:BledDest,2021-01-15], [user:adedalic,2021-01-15] <spoiler summary="Tutorial"> [tutorial:1473A] </spoiler> <spoiler summary="Solution (Neon)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; while (tc--) { int n, d; cin >> n >> d; vector<int> a(n); for (int& x : a) cin >> x; sort(a.begin(), a.end()); cout << (a.back() <= d || a[0] + a[1] <= d ? "YES" : "NO") << endl; } } ~~~~~ </spoiler> [problem:1473B] Idea: [user:BledDest,2021-01-15] <spoiler summary="Tutorial"> [tutorial:1473B] </spoiler> <spoiler summary="Solution (Neon)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { auto mul = [](string s, int k) -> string { string res = ""; while (k--) res += s; return res; }; int tc; cin >> tc; while (tc--) { string s, t; cin >> s >> t; int n = s.length(), m = t.length(); ...
int n, s, t; T flow; vector lst; vector d; vector<vector> g;

Full text and comments »

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