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

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

Results

1.
By Rhodoks, history, 4 years ago, In English
Codeforces Round #810 Editorial Sorry for the late editorial. May this editorial help you. If you have questions, feel free to ask. [problem:1711A] <spoiler summary="hint1."> The minimal weight is at least $1$ since $1$ divides any integer (so $1$ divides $p_1$). </spoiler> <spoiler summary="solution"> Since $k+1$ does not divide $k$, a permutation with weight equal to $1$ is: $[n,1,2,\cdots,n-1]$. </spoiler> <spoiler summary="code"> ~~~~~ #include <bits/stdc++.h> using namespace std; void work() { int n; cin>>n; cout<<n<<' '; for (int i=1;i<n;i++) cout<<i<<' '; cout<<endl; } int main() { int casenum=1; cin>>casenum; for (int testcase=1;testcase<=casenum;testcase++) work(); return 0; } ~~~~~ </spoiler> [problem:1711B] <spoiler summary="hint1."> See the party as a graph. </spoiler> <spoiler summary="hint2."> Divide the vertices into two categories according to their degrees' parity. </spoiler> <spoiler summary="solution"> Let's consider ...
: $cnt_{101}+cnt_{010}>0$ $cnt_{110}+cnt_{001}>0$ then we use digit dp: $dp [n][i][j]$ means when, LL dp[MAXN][8][8]; string s; int main() { cin>>s; dp[0][0][0]=1; for (int i=0;i, then we use digit dp: $dp[n][i][j]$ means when we consider first $n$ bits, state of reaching the

Full text and comments »

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

2.
By MikeMirzayanov, history, 22 months ago, translation, In English
New Year's Eve Update: Random Problems for Mashups Hello, Codeforces! Only a couple of days remain until 2025. To wrap up the year, I'm bringing an update &mdash; I hope you'll find it useful. Now, you can automatically find and add random problems for your mashup based on a range of criteria and restrictions. The problems are sourced from the archive, and unusual problems are automatically excluded. So, click the "Add random problems" link under the problem list and proceed to the addition form. <center> <img style="zoom:75%;" src="/predownloaded/b9/25/b925e4d00215ff2e408cc81c2629936df72dce38.png"/> </center> Here's what you can do: * Exclude problems that registered mashup participants have solved/attempted/authored (a problem will be excluded if at least one registered participant is familiar with it), * If the mashup belongs to a group (e.g., your training group), exclude all problems from other contests in that group, * Exclude problems with subtasks &mdash; such problems are often interconnected or referenc...
automatically; * "p D ratings:-1200 tags:greedy,dp": a problem with a difficulty level, contest letter assigned automatically; * "p D ratings:-1200 tags:greedy,dp": a

Full text and comments »

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

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

Full text and comments »

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

4.
By parveen1981, history, 5 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...
Knapsack problem](https://codeforces.me/blog/entry/59606) - [Digit DP ](https://codeforces.me/blog, ://codeforces.com/blog/entry/59606) - [Digit DP ](https://codeforces.me/blog/entry/53960) - [[Tutorial]A

Full text and comments »

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

5.
By Um_nik, history, 4 years ago, In English
Pro Tips - get them while they are free More tips to use while studying under my tutoring [here](https://um-nik.notion.site/Pro-Tips-8b923b0dc7c94770824bdf4184afc43c). ## Stop caring about the rating Unless there are prizes involved, your position in the standings makes no difference. I can feel awful after winning a contest if I know that I could solve one more problem. Or I can feel OK losing a bunch of rating points knowing that I solved everything I could.  Because rating is just a number. It is highly volatile and it depends on other people, not only on your skill. But solving problems is totally up to you. And you should evaluate yourself not based on some random metric, but on your honest feeling whether you performed up to your expectations. Your sense of self should be under your control, don't get hung up on some imaginary value, you cannot reduce your progress to a single number. ## Don't use more than one account Rating is just a number. Do not be afraid to lose your colour. You’ll get it back in no t...
problems Basically this: [On "is this greedy or DP", forcing and rubber bands](https://codeforces.com, Basically this: [On "is this greedy or DP", forcing and rubber bands](https://codeforces.me/blog, But Um_nik, the best way to learn how to do X, is to do X. I want to be good at DP, therefore I, True statement, wrong conclusion. What you want to be good at is not only solvingDP problems, but, You can (and should) try to think “Can I do greedy? Can I do dp?” and similar. What you shouldn’t

Full text and comments »

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

6.
By zscoder, history, 6 years ago, In English
[Tutorial] Generating Functions in Competitive Programming (Part 1) Hi everyone! Inspired by the recent [Codeforces Round 641](https://codeforces.me/contest/1349), I decided to write an introductory tutorial on generating functions here. I am by no means an expert in generating functions so I will write about what I currently know about them. [user:MiFaFaOvO,2020-05-15] has written a really interesting [blog](https://codeforces.me/blog/entry/76447) here on Codeforces about more advanced applications of generating functions, but I think there is no English tutorial on the basics of this topic yet (or at least on CP sites). Thus, I would like to share about this topic here. I plan to split this tutorial into two parts. The first part (this post) will be an introduction to generating functions for those who have never learned about them at all, and some standard examples and showcases of generating functions. The second part will be a collection of several applications of generating functions in CP-style problems. If you are already familiar with ge...
. What is the simplest dp you can come up with?, By precomputing binomial coefficients, this is an $O(n^2)$ dp, which should be sufficient for a Div

Full text and comments »

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

7.
By antontrygubO_o, 6 years ago, In English
Some thoughts on recent discussions Hello everyone! I finally decided to write some response/explain my view after all recent discussions of my problems and rounds I coordinate, and I would like to make a few points. **1.** After some recent contests there were a lot of comments saying that Data structure problems should appear as easy problems (say, D2A-D2D in a Div2 of $6$ problems) ![ ](https://i.imgur.com/fmA8zgE.png) ![ ](https://i.imgur.com/m4pJLv6.png) ![ ](https://i.imgur.com/JsryG77.png) I don't think I agree with this. To begin with, I don't think that having Data Structure problem is a requirement for a good contest at all, not just in first few positions. ![ ](https://i.imgur.com/VWAOgxg.png) However, for positions D2A-D2D, I just don't see a way to properly include data structure problems. Take some Data Structure problem, it consists from two parts: <ul> <li> Knowing/implementing the Data Structure </li> <li> Actually thinking about the problem, and how this Data Structure...
impossible hard to create an interesting DP/Binary Search/Graph problem which could, **2.** A lot of people lately are sad because graphs, dp and all other topics don't appear now, /maps as Data Structures. **2.** A lot of people lately are sad because graphs, dp and all other, And I don't want to accept standard problems on DP/Binary Search/Graphs just to make the set more, [problem:1372E] and [problem:1363F] are DP.

Full text and comments »

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

8.
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 ...
First, we consider the naive dp: $f_{i,j}=f_{i-1,j} + f_{i-1,j-1} \cdot (j+a_i)$. Let $g_{i,j

Full text and comments »

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

9.
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...
3 # it is possible that there is no larger multiple of k to be the previous gcd 4dp[k, = weight; i < dp.size(); i++) { 3 dp[i] -= dp[i - weight]; 4 } ~~~~~, length $n$. A classical bitset solution is to let $\mathrm{dp}[v]$ be a bitset such that, numbers, with each element being a divisor of the previous one. Define $\mathrm{dp}[k]$ as the, there can be only $O(\sqrt m)$ rocks (see next point). Now you can use a classicalDP algorithm but, ways in $\mathrm{dp}$ and check whether it is nonzero. Since the numbers will become very large, we, $, we associate every position in the array $\mathrm{dp}[v]$ with a descendant of $v$. The array, $. You are maintaining an array $\mathrm{dp}[i]$, where $\mathrm{dp}[i]$ is the number of ways to pick a, (dp[v])-1: 7 for j in in 0..length(dp[w])-1: 8 # calculate, A classical bitset solution is to let $\mathrm{dp}[v]$ be a bitset such that $\mathrm{dp}[v][u] = 1, For any $u$, let $\mathrm{dp}[u][k]$ be the maximum pair $\left< t, s \right>$, such that, Notice however, that the array $\mathrm{dp}$ does not in any way depend on the order the items were, Suppose you are solving a tree problem with dynamic programming. Your DP states look like this: for, The transitions to this DP can be calculated in a way similar as discussed above. For a given $u, ~~~~~ 1 # we go from large to small so that the already updated dp values won't affect any

Full text and comments »

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

10.
By zscoder, history, 10 years ago, In English
[Tutorial] Non-trivial DP Tricks and Techniques Hi everyone! Today I want to share some DP tricks and techniques that I have seen from some problems. I think this will be helpful for those who just started doing DP. Sometimes the tutorials are very brief and assumes the reader already understand the technique so it will be hard for people who are new to the technique to understand it. Note : You should know how to do basic DP before reading the post DP + Bitmasks ------------------ This is actually a very well-known technique and most people should already know this. This trick is usually used when one of the variables have very small constraints that can allow exponential solutions. The classic example is applying it to solve the Travelling Salesman Problem in $O(n^{2} \cdot 2^{n})$ time. We let $dp[i][j]$ be the minimum time needed to visit the vertices in the set denoted by $i$ and ending at vertex $j$. Note that $i$ will iterate through all possible subsets of the vertices and thus the number of states is $O(2^{n} \cdo...
[Tutorial] Non-trivial DP Tricks and Techniques, 2^{n})$ time. We let $dp[i][j]$ be the minimum time needed to visit the vertices in the set denoted, already fixed the values of $dp[1], dp[2], ..., dp[i - 1]$. For a fix blocked cell $S_{i}$, we'll do so by, from $\{1, 2, ..., A\}$, i.e. $dp[A][i]$., jump. This type of intuition might come in handy to optimize your dp and turn the naivedp into an, naive $O(n^2)$ dp manually so there's no need to worry about it., "Connected Component" DP ------------------, $, which prompts us to apply dp + bitmask here. Note that for any pair $b_{i}, b_{j}$ with $i \neq j, 1. We place the current number $a_{i}$ in its own group : Then, $dp[i][j][val] += v$., 2. We place the current number $a_{i}$ in one of the open groups, but **not close it** : Then, $dp, 3. Open a new group with minimum = $a_{i}$ : Then, $dp[i][j+1][val] += v$., 4. Close an open group by inserting $a_{i}$ in one of them and **close it** : Then, $dp[i][j-1][val, Change the object to dp ------------------, DP + Bitmasks ------------------, Finally, with the values of $b_{i}$, we can calculate $dp[2A][\cdot]$ the same way as the last, Here are some other problems that uses bitmask dp :, Hi everyone! Today I want to share some DP tricks and techniques that I have seen from some, Let $dp[i][j]$ be the number of permutations of length $i$ with $j$ inversions. Then, $dp[i][j, Let $dp[i][j][k]$ be the number of ways such that when we inserted the first $i$ elements, there, Let $dp[i][j][k][l]$ be the number of ways to insert the first $i$ elements such that :, Note : You should know how to do basic DP before reading the post, Note that the number of blocked cells is not too large though, so we can try to dp on them. Let $S, Now, let $dp[i]$ be the number of ways to reach the $i$-th blocked cell (assuming it is not blocked, Now, let $dp[i][j]$ be the sum of values of all valid sequences of length $j$ where values from $1, Now, we let $dp[i][j]$ be the minimum answer one can get by changing the first $i$ elements such, Now, we'll use the idea from the last example. We already know how to calculate $dp[i + 1][\cdot, So, the most direct way of doing dp would be let $dp[i][j]$ be the number of gems Mr. Kitayuta can, Sometimes, the naive dp solution to a problem might take too long and too much memory. However, Suppose we calculated $dp[i][j]$ for all $0 \le j \le K$. We have already figured out how to, Suppose we want to calculate $dp[2A][n]$. Then, we consider for all possible $a$ the sum of the, The answer can be found as $dp[n][0][0] + dp[n][0][1] + ... + dp[n][0][k]$., The base case, $dp[1]$ can be calculated as the number of ways to reach $S_{1}$ from the starting, The recurrence is $dp[i][j] = dp[i - 1][j] + i \cdot dp[i - 1][j - 1]$, depending on whether $i$ is, This is a classic example. If the board was smaller, say $3000 \times 3000$, then the normal 2Ddp, This is the end of this post. I hope you benefited from it and please share your owndp tricks in, Thus, we can calculate $dp[2i][\cdot]$ and $dp[i + 1][\cdot]$ in $O(n^2)$ and $O(n)$ respectively, Thus, we have found a way to obtain $dp[2i][\cdot]$ from $dp[i][\cdot]$ in $O(K^2)$., To complete the solution, we first write $N$ in its binary representation and compute thedp values, Usually, when doing DP + Bitmasks problems, we store the subsets as an integer from $0$ to $2^{n, You might be wondering : How can we apply dp when $N$ is as huge as $10^{9}$? We'll show how to

Full text and comments »

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

11.
By TheOneYouWant, history, 6 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 ...
= dp(n, n); if(ans > 1e9) ans = -1; cout << ans << endl; } return 0, int dp(int i, int j) { if(j == 0) return 0; int &ans = cache[i][j]; if(ans != -1

Full text and comments »

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

12.
By shiven, history, 23 months ago, In English
A summary of what passes for an Indian ICPC Contest, apparently The online round for the India’s ICPC was held on 23rd. And also a week before that. The first time around, the organisers tried debuting a self-hosted DOMjudge instance. That didn’t go too well, so a recontest was scheduled on CodeChef. If you’re not too familiar with the Indian ICPC system — this online prelims is used to select teams that can participate in the offline regionals. From a single university, usually approx. 2 teams (for the top unis) or 1 (for almost all unis that aren’t in top-15) qualify. As you could guess, it’s quite easy for good teams to miss a spot. Looking at the first contest’s rankings, teams from rank 2 to 100+ all had 4 solves. Owing to severe system issues in the first contest, the time penalties weren’t too reliable differentiators, leading to the recontest this Saturday. In hindsight, we forgot to be grateful for the problemset and reliable testcases the first time. I’m sure everyone agrees that the basic requirements (ignoring all other stuff...
ACed with a DP with $N^2 \log N$ states. It seems correct to us, but given that the test-cases, - GPT writes an obvious $O(N^3)$ DP. Works. - $O(N)$ greedy. Wrong, ofc. But works. - $O(N)$DP

Full text and comments »

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

13.
By Radewoosh, history, 8 years ago, In English
Blogewoosh #6 Hello, codeforces! Sorry for the long break, but the last weeks of holidays and the first weeks of academic year took my attention. I hope today's trick will make you forgive me. :P I invented this trick a few years ago, but for sure I wasn't first, and some of you already know it. Let's consider the following **interactive** task. There are $n$ ($1 \leq n \leq 10^5$) hidden integers $a_i$, each of them from range $[1, 10^{18}]$. You are allowed to ask at most $103000$ queries. In one query you can choose two integers $x$ and $y$ ($1 \leq x \leq n, 1 \leq y \leq 10^{18}$) and ask a question ''Is $a_x \geq y$?'' The task is to find the value of the greatest element in the hidden array. The checker **isn't** adaptive. Unfortunately, this task is only theoretical, and you cannot solve it anywhere, but it'll turn out, that solution can be handy in many other, much more complicated problems. [cut] $ $ Even beginners should be able to quickly come up with a solution which ask...
seems to be enough. It also can be proven or checked with DP/Monte Carlo, that probability that the

Full text and comments »

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

14.
By -is-this-fft-, history, 4 years ago, In English
On "is this greedy or DP", forcing and rubber bands #### Introduction When it comes to "problem-solving techniques", there are roughly 3 levels: 1. Concrete algorithms (Kruskal's algorithm, Li-Chao tree, fast Fourier transform) 2. General patterns (dynamic programming, greedy, square-root decomposition) 3. Meta-strategies ("how do I even go about solving this problem?") There is some grey area, but in general this classification works well. [Many tutorials](https://codeforces.me/catalog) have been written about ideas that fall into 1 or 2. But very little has been written about the third category. On the catalog, I think the only blogs that really qualify are [this](62730) and [this](20548). There is also [this](92248?#comment-809401) valuable comment. As to why there is so little written, I think I can identify two reasons. - Most strong contestants don't really consciously think about these. After solving a problem with FFT, it's hard not to know you used FFT. If you used DP, even if you did it without thinki...
On "is this greedy or DP", forcing and rubber bands, FFT, it's hard not to know you used FFT. If you used DP, even if you did it without thinking that, can make an algorithm out of. - Solve the new and simpler problem directly, withDP, greedy or, greedy algorithm. - Not greedy does not imply DP. - This is simply the wrong question to ask at, it be solved with DP?". There are many reasons one might ask this, but I'm certain that in some, or use some other, usually misguided, intuition to tell whether it is DP, greedy, or something else, problem with FFT, it's hard not to know you used FFT. If you used DP, even if you did it without, same. Doing greedy or DP happens at the end of your thought process, not at the beginning of it., solve this problem directly by DP or greedy or some secret algorithm that only reds know about. In, true in hard CP problems. You might do some greedy things and some DP, but knowing that in advance, using DP. How to exactly come up with this transformation and how to use DP for the new problem are, , possibly a greedy algorithm or DP., , therefore it is DP" would never have reached here.**, DP. For example, I once saw some segment tree code that was just complete nonsense. And this is, Maybe this technique of guessing and forcing DP or greedy works well enough for easy problems and, Similarly, there are many questions and blogs of the form "is this DP or greedy". For example, This is the perfect problem where misguided intuition will lead you to think aboutDP. Maximizing

Full text and comments »

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

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

Full text and comments »

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

16.
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"; } } ...
(1, n, 1); } int dp = qmn(a[i - 1], a[i - 1]); if

Full text and comments »

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

17.
By Radewoosh, history, 8 years ago, In English
Blogewoosh #4 Hello, codeforces! It's time to continue the series of Polish tasks. I've decided to write about my own task one more time. Its name is "cook" ([you can submit here](https://szkopul.edu.pl/problemset/problem/9NFtPM59qGWa7wdn570ifuP0/site/?key=statement)). The task isn't very hard, but it uses cute (in my opinion) trick. The statement goes as follows: There is a cook in a restaurant. He has $n$ ($1 \leq n \leq 10^6$) orders which he must fill. Every order is a piece of paper, and all orders are speared on a spindle (sharp stick with pierced pieces of paper) in a fixed order which cannot be changed. Normal cook would just take orders one by one from the top of the spindle and fill them in this order, but the cook in this task has supernatural cooking powers and can combine orders to fill them faster. In particular, if at some moment there are $k$ out of $n$ orders still on the spindle, he can choose one of three options: $---$ He can take the topmost piece of paper and fill this...
denote by $DP[i][j]$ minimum amount of time in which the cook can finish his work if there are last, energy level, so everything in the task suggests dynamic programming. So, let's denote by $DP[i][j, . Without cook's third move, we'd be able to keep only last two columns of $DP $, but to use the, So, how to optimize the memory? Let's keep two columns of $DP$ (initially columns $-1$ and $0

Full text and comments »

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

18.
By Errichto, 6 years ago, In English
Matrix Exponentiation tutorial + training contest tl;dr &mdash; video tutorial https://www.youtube.com/watch?v=eMXNWcbw75E and codeforces GYM training https://codeforces.me/gym/102644 (register by finding this contest in GYM instead of using the link directly) video editorial: [part 1 (ABCDEF)](https://www.youtube.com/watch?v=kQuCOFzWoa0) and [part 2 (GHI)](https://www.youtube.com/watch?v=RA_SpxP2t54) codes to all 9 problems: https://github.com/Errichto/youtube/tree/master/matrix-exponentiation Prerequisites: binary exponentiation and iterative dp (you don't need to know matrices) The youtube tutorial ([link](https://www.youtube.com/watch?v=eMXNWcbw75E)) focuses on intuition and graph-like visualization . Or, if you prefer, below is a shorter (less detailed) text tutorial instead. You can practice by solving a set of 9 educational problems in GYM https://codeforces.me/gym/102644. ABCD are easy, EF medium, GHI are hard. If you are stuck, see hints below or watch the full solution analysis &mdash; [part 1 (ABCDEF)](https:...
You need to first solve a problem with dp in $O(1)$ space. Here, _order_), which is equal to the number of states (variables) you need in space-efficientdp. We had $s=2, ~~~~~ #include using namespace std; const, $. Try to solve it with dp in $O(64)$ space and create an array with ALL variables you need to, ://codeforces.com/gym/102644/problem/C)) by first implementing space-efficient dp with transitions of form, If something can be solved with dp in $O(1)$ space, we can usually speed it up later with matrix, Prerequisites: binary exponentiation and iterative dp (you don't need to know matrices), This is a much harder version of problem E, where we already needed to express space-efficientdp, When doing space-efficient dp, avoid using index $i$ from a for-loop. We can use matrix

Full text and comments »

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

19.
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...
Assume you write a profile dp. Or a 3-layer bfs. Or something else, where you need sometimes to

Full text and comments »

  • Vote: I like it
  • +756
  • 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...
) { if (!dp[mask][pr].empty()) { add(0, dp[mask][pr] + "|" + e.e, mask | e.t); add, cout << dp[mask][0] << endl; }, if (e.p == 1) { for (int mask = 0; mask < FULL; ++mask) { if (!dp[mask][2].empty, string dp[1 << 8][3];, void add(int pr, const string& s, int mask) { if (dp[mask][pr].empty() || ls(s, dp[mask][pr

Full text and comments »

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

21.
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...
11361 UVA (4) //digit DP, http://codeforces.me/contest/118/problem/C (4) //[NICE] — Try each digit (iterate in waves), http://codeforces.me/contest/794/problem/F (7) //Digit by digit! (N*log(N)*100 ~passes,2017-10-19), http://www.spoj.com/problems/CPCRC1C/ (4) //Digits dp (return pair), http://www.spoj.com/problems/DRACULA/ (4) //NICE Digit-DP (Both sides) — iterate by sum, http://www.spoj.com/problems/EQ2/ (4) //NICE: Digit + Carry (from back) — iff-party, http://www.spoj.com/problems/KOPC12H/ (4) //NICE Digit-DP, http://www.spoj.com/problems/NOSQ/ (3) //Sieve + Digit check

Full text and comments »

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

22.
By Errichto, 8 years ago, In English
Stream I want to try streaming competitive programming. The goal is to make it educational so I will be talking a lot, also answering (at least some) questions. I'm planning three completely different streams to see what format to use: 1. Solving random easy-medium problems. 2. Solving old problems from Polish olympiad. 3. Post-contest stream, assuming I'm a setter or tester of a contest. Similar to what [user:scott_wu,2018-09-27], [user:ecnerwala,2018-09-27] and [user:stevenkplus,2018-09-27] did. Any thoughts, ideas? The first stream will most likely be on Sunday, starting around 7-8pm CEST. I will use Twitch and talk in English only. These first streams should show me and you whether it's cool and useful, and whether I like doing it. Also, I will try to make the video accessible later. **--- UPDATE ---** The first stream will start on Saturday at 10am CEST (check your [timezone](https://www.timeanddate.com/worldclock/fixedtime.html?msg=Errichto+Stream+%231&iso=2018...
from the round first. So, the main topic is hard DP problems, I guess. I prefer to stream on Youtube

Full text and comments »

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

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

Full text and comments »

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

24.
By flash_7, history, 9 years ago, In English
Digit DP Wrote this article a long ago but during solving a problem recently thought of sharing this article publicly. Hope it will help some contestants to understand the idea clearly. Digit dp is a very easy technique and also useful to solve many dynamic programming problems. Seeing the name “Digit DP” it’s easy to guess that we are going to do something using the digits. Yes we are actually going to play with digits. Let’s explain the concept using a classical problem. #### Problem How many numbers **x** are there in the range **a** to **b**, where the digit **d** occurs exactly **k** times in **x**? There may have several solutions including number theory or combinatorics, but let’s see how we can solve this problem using digit dp. #### Solve for range (zero to a) Using digit dp we always focus on building a number satisfying all the conditions. If we finally manage to build that number then we say, yes we have got one ;-) But how we’ll build that number? For the time being let...
Digit DP, build the sequence. In each recursive call we’ll place a digit in our current position and will call, combinatorics, but let’s see how we can solve this problem using digit dp., find if a valid **t** exist? If we placed any digit in our previous position which was smaller than, publicly. Hope it will help some contestants to understand the idea clearly. Digit dp is a very, there is an extra condition which is, digit **d** will have to occur exactly **k** times in, #### Final DP States If we have understood everything so far then it's easy to see that we need, #### Information we need to place a digit at the current position Let’s say during the building of, #### Solve for range (zero to a) Using digit dp we always focus on building a number satisfying, ://www.spoj.com/problems/TAP2012C/en/) 8. [Digit Count](https://vjudge.net/problem/LightOJ-1122) 9, Digit dp is a very easy technique and also useful to solve many dynamic programming problems, You can see that, in the sequence **sq** the left most digit is actually the most significantdigit, digit greater than b[pos]. Because then the number will become larger than **b**.

Full text and comments »

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

25.
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;...
(int i = 1; i <= n; i++) cin >> a[i]; dp[0][0] = 1; for (int i = 1; i <= n; i, doing DP., ++) { add(i - 1, -A); for (auto [x, w] : p[i]) add(x, w); dp[i] = max(dp[i - 1, ; i++) { if (q[l] < i - K) l++; dp[i] = dp[q[l]] + a[i], pre[i] = q[l, ; while (T--) { const int N = 200000 + 5; int n, a[N], dp[N], buc[N]; cin, DP+divide and conquer , Our goal is to compute the expected sum of all the terms, which can be nicely combined withDP:, This dp can be calculated in $O(n)$ since we can store for each $x$ what the minimum $dp_j$ which, We can write a DP. $dp_i$ denotes the minimum number of points we do not delete when considering, int n, K, a[N], pre[N * 2]; long long dp[N * 2], ans;, int n, k, A, c[M << 1][2], dp[N]; vector> p[N];, int n, m, v, a[N], coef[N], dp[N][N];

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

29.
By ko_osaga, history, 4 years ago, In English
OR Convolution for Common People Several years ago, a wise person told me that a convolution on a bitwise operator is possible: Given $A, B$ of size $2^N$, you can compute $C[i] = \sum_{j \oplus k = i} A[j] B[k]$ $C[i] = \sum_{j \land k = i} A[j] B[k]$ $C[i] = \sum_{j \lor k = i} A[j] B[k]$ in $O(2^N N)$ time. Cool! I asked a wise person, how such things are possible. A wise person replied, _"Of course you know how FFT works, let's begin with Fast Welsh-Hadamard Transform..."_ I said, No. I don't know how FFT works. Thank you. Then I just threw it into my ICPC teamnote. Years have passed, I still don't know how FFT works, and while writing some stupid essay, a random idea came to my mind. I wondered, "Does nobody really know this? Why anyone didn't explain OR convolution this way?". I searched on Google, and nobody was telling things this way, so this is certainly not a common explanation. But why? It should be. Let me use my time to change things for good. ## Sum of Subsets For convenience, I'll...
Given an array $A$, how to compute $(\sum_{j \subseteq i} A[j])$? This is just a [sum-of-subsetsDP

Full text and comments »

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

30.
By 4fecta, history, 5 years ago, In English
An Introduction to Plug DP So I realized that there are literally 0 resources written in English on Plug DP, which is one of my favourite DP tricks/techniques that I know of so far. Thus, I hope this serves as a soft introduction for English speakers to this technique, and maybe sheds some light on how powerful it can be. Before we start, I would recommend having a solid understanding of bitmask DP in general in order to get the most out of this blog. Now, let's begin. ### What is Plug DP? In short, Plug DP is a bitmasking technique that allows us to solve complicated problems with relatively simple states and transitions. To illustrate Plug DP in its most primitive form, let's visit a rather classical problem: **How many ways can we fully tile an $N \times M$ grid with $1 \times 2$ dominoes?** This problem can be solved with a standard row-by-row bitmasking approach, but the transitions for that DP state is annoying and unclear at best. Instead, let's investigate an approach that uses a slightly differ...
An Introduction to Plug DP, bitmask of length $M+1$, so the DP state which the tiling below belongs to is $ dp[3][4][101010010_2, process row $i$, we will transfer all the values stored in $dp[i - 1][M][mask]$ to $dp[i][0][mask, set dp[0][m][0] = 1; //base case for (int i = 1; i <= n; i++) { for (int msk = 0; msk, that DP state is annoying and unclear at best. Instead, let's investigate an approach that uses a, ### What is Plug DP?, And that was a quick overview of Plug DP! With a firm grasp on the concepts we can easily extend, In short, Plug DP is a bitmasking technique that allows us to solve complicated problems with, Our base case will be $dp[0][M][0] = 1$, and you can see how this easily fits in from the previous, So I realized that there are literally 0 resources written in English on Plug DP , which is one of

Full text and comments »

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

31.
By icecuber, 7 years ago, In English
CSES DP section editorial Edit: More dp tasks have been added to CSES since this blog was created. For solutions to those problems, check out [user:UnexpectedValue,2023-02-14]'s blog [here](https://codeforces.me/blog/entry/111675). I'm using bottom-up implementations and pull dp when possible. Pull dp is when we calculate each dp entry as a function of previously calculated dp entries. This is the way used in recursion / memoization. The other alternative would be push dp, where we update future dp entries using the current dp entry. I think [CSES](https://cses.fi/problemset/list/) is a nice collection of important CP problems, and would like it to have editorials. Without editorials users will get stuck on problems, and give up without learning the solution. I think this slows down learning significantly compared to solving problems with editorials. Therefore, I encourage others who want to contribute, to write editorials for other sections of CSES. Feel free to point out mistakes. ## Dice Combin...
CSES DP section editorial, : price) cin >> v; for (int&v : pages) cin >> v; vector> dp(n+1,vector(x+1,0, didn't include it, then there are dp[i-1][x] possibilities, or we included it, and there aredp[i-1, greedy solution of always subtracting the maximum digit is also correct, but we are practicingDP, number of ways to make sum x ending with a 3 is dp[x-3]. Summing over the possibilities givesdp[x, ## Removing Digits (1637) `dp[x] = minimum number of operations to go from x to zero.`, ) cin >> v; vector> dp(n+1,vector(max_sum+1,false)); dp[0][0] = true, > dp(na+1, vector(nb+1,1e9)); dp[0][0] = 0; for (int i = 0; i <= na; i, I'm using bottom-up implementations and pull dp when possible. Pull dp is when we calculate eachdp, In this problem dp[l][r] depends on dp[l+1][r], and therefore we need to compute larger l before, Note that the greedy solution of always subtracting the maximum digit is also correct, but we are, When considering a number x, for each digit in the decimal representation of x, we can try to, int main() { int mod = 1e9+7; int n, m; cin >> n >> m; vector> dp(n,vector, int main() { int mod = 1e9+7; int n; cin >> n; vector dp(n+1,0); dp[0] = 1, int main() { int mod = 1e9+7; int n; cin >> n; vector> dp(n, vector(n, int main() { int n; cin >> n; vector dp(n+1,1e9); dp[0] = 0; for (int i = 0; i, int main() { int w, h; cin >> w >> h; vector> dp(w+1,vector(h+1)); for, vector dp(coords, 0); for (int i = 0; i < coords; i++) { if (i > 0) { dp, vector dp(target+1,0); dp[0] = 1; for (int i = 1; i <= target; i++) { for (int j, vector dp(target+1,1e9); dp[0] = 0; for (int i = 1; i <= target; i++) { for (int j, vector> dp(n+1,vector(target+1,0)); dp[0][0] = 1; for (int i = 1; i <= n; i, vector> dp(n,vector(n)); for (int l = n-1; l >= 0; l--) { for, vector> dp(n,vector(target+1,0)); dp[0][0] = 1; for (int i = 1; i < n; i

Full text and comments »

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

32.
By Errichto, 16 months ago, In English
DP Group Class in August 2025 _The blog publish date is incorrect, should be around 12.07.2025. CF saved the draft date._ Hi, I'm organizing paid group classes on Dynamic Programming in August. Last year, I did something similar with general problem-solving ([link](https://codeforces.me/blog/entry/129878)). There will be two groups of different style and difficulty. Each group gets 8 lessons of 1h30m each, from 28.07.2025 to 24-31.08.2025. Group size up to 12 people. You get access to recordings and problems from both groups, but you should actively attend only one. There's a lot of homework, some to be discussed next lesson. I will create new original CF/Polygon problems, especially for the easy group. These problems will eventually be published for everybody! **Price**: 250 EUR with a small country-based discount. **Registration**: You should pay via [link (Stripe)](https://buy.stripe.com/7sY3cx2nD5Oh8CQ7w96wE03) and choose the group there. I will send you the Discord invite link via e-mail. Co...
DP Group Class in August 2025, #### Easy group, solving dp problems, #### Hard group, dp techniques, **Prerequisites**: Prefix sums, knapsack, bitmasks. Being able to solve (almost) any easydp, There is a DP solution :) , There will be a few non-dp problems to help you distinguish DP vs. Greedy., We will not cover: LIS (too easy), all-directional tree DP (it's more about trees) anddigit dp

Full text and comments »

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

33.
By neal, 8 years ago, In English
Quick unofficial editorial for Educational Round 59 (Div. 2) Continuing with the theme from last time, here's a quick writeup of my approaches: #### [problem:1107A] Since we just want to make two numbers such that the first number is smaller than the second, our best bet is to use only the first digit for the first number and the rest of the digits for the second number. Note that since the numbers can have up to 300 digits we shouldn't actually evaluate the second number. Instead, since the digits only include 1 through 9, we can handle that case by checking the number of digits. Code: [submission:49002957] #### [problem:1107B] The key observation is that the digital root of an integer $k$ is the single-digit number $1 \leq d \leq 9$ such that $k \equiv d \bmod 9$. You can prove this by noticing that $10^p \equiv 1 \bmod 9$ for all $p$. Once we observe this, finding the $k$-th number is very simple; see the code: [submission:48993705] #### [problem:1107C] Since we are only allowed to push the same button $k$ times in a row, let's do...
than the second, our best bet is to use only the first digit for the first number and the rest of, #### [problem:1107E] We set up a DP on (start index, end index, number of consecutive digits, - Cash in on our consecutive digits at the start and recurse on $\text{dp }(\text{start} + 1, \text

Full text and comments »

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

34.
By Lewin, 9 years ago, In English
Good Bye 2017 Editorial Here's the editorial. Hope you have a happy new year! Code can be found here: https://www.dropbox.com/sh/i9cxj44tvv5pqvn/AACQs7LLNyTZT-Gt_AMf7UQFa?dl=0 <spoiler summary="New Year and Counting Cards"> Let's start off a bit more abstractly. We would like to know if the statement "if P then Q" is true, where P and Q are some statements (in this case, P is "card has vowel", and Q is "card has even number"). To do determine this, we need to flip over any cards which could be counter-examples (i.e. could make the statement false). Let's look at the truth table for if P then Q (see here: http://www.math.hawaii.edu/~ramsey/Logic/IfThen.html). The statement is only false when Q is false and P is true. Thus, it suffices to flip cards when P is true or Q is false. To solve this problem, we need to print the count of vowels and odd digits in the string. <spoiler summary="stats"> First solve: [user:ksun48,2017-12-29] at 00:01:01 Breakdown of results for submissions that passed...
For a fixed digit, we can compute this dp table in $O(n^2)$ time, and then compute the answers to, This is a digit dp problem. Let's try to solve the subproblem "How many ways can the i-thdigit be

Full text and comments »

Tutorial of Good Bye 2017
  • Vote: I like it
  • +336
  • Vote: I do not like it

35.
By zscoder, history, 6 years ago, In English
[Tutorial] Generating Functions in Competitive Programming (Part 2) Welcome to Part 2 of my tutorial on generating functions. The [first part](https://codeforces.me/blog/entry/77468) focused on introducing generating functions to those without any background in generating functions. In this post, I will demonstrate a few applications of generating functions in CP problems. Let us start with some relatively straightforward examples. Note: Unless stated otherwise, all computations are done modulo a convenient prime (usually $998244353$). Also, $[n]$ denotes the set $\\{1,2,...,n\\}$. ### Blatant Applications in Counting Problems **Problem.** [AGC 005 Problem F](https://atcoder.jp/contests/agc005/tasks/agc005_f) You have a tree $T$ with $n$ vertices. For a subset $S$ of vertices, let $f(S)$ denote the minimum number of vertices in a subtree of $T$ which contains all vertices in $S$. For all $1 \le k \le n$, find the sum of $f(S)$ over all subsets $S$ with $|S| = k$. Constraints: $n \le 2 \cdot 10^{5}$. <spoiler summary="Solution"> First, ...
There is a simple $O\left(\frac{n^2}{k}\right)$ dp solution (try to, easier variant of this problem using a doubling trick to perform dp. Now, let's describe a much, How do we expand the terms quickly? We can use dp! Go through the brackets one by one, and maintain, }$ with dp. Note that there are only $O(1)$ nonzero values of $f_{i,j}$, so you can actually just iterate

Full text and comments »

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

36.
By arvindf232, 4 years ago, In English
Codeforces Round #822 (Div.2) Editorial Thank you for your participation! [1734A &mdash; Select Three Sticks](https://codeforces.me/contest/1734/problem/A) ------------------ We first sort the array $a$ in non-decreasing order. Denote the indices of the elements that we choose from $a$ to be $x$, $y$, and $z$, where $1 \le x < y < z \le n$, and the final value (after performing the operations) of the concerned elements to be $v$. The minimum required number of operations is then $|a_x-v|+|a_y-v|+|a_z-v|$. It is well-known that such expression attains its minimum value when $v$ is the median of $a_x$, $a_y$, and $a_z$. Since the array $a$ has already been sorted, it is best to assign $v$ to be $a_y$. Our expression then becomes $|a_x-a_y|+|a_y-a_y|+|a_z-a_y|=(a_y-a_x)+0+(a_z-a_y)=a_z-a_x$. We would like to minimize the value of $a_z$, which implies $z$ should be as small as possible since $a$ is sorted. It is clear that taking $z=y+1$ would minimize the value of the expression. Similarly, we can show that we ...
###1. Digit DP solution, There are many other digit DP approaches that give similar time complexity. The constraints should, This can be solved with digit DP. We process the bit position from $\lceil \log(\max) \rceil$ down

Full text and comments »

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

37.
By kpw29, 6 years ago, In English
Meet IT Codeforces Round Editorial Thank you very much for taking part in the contest! <spoiler summary="Contest timeline"> - -0:05. Starting the chat with the Questions Answering team: [user:tnowak,2020-11-15] and our beloved coordinator [user:antontrygubO_o,2020-11-15]. We hope that there won't be that many questions :) - -0:01. One minute to go! I hope that everything goes smoothly. I'm so afraid of posting the editorial accidentally that I moved this timeline into another blog... - 0:01. First blood in Div2! Congratulations to [user:majorro,2020-11-15]!. - 0:03. First blood in Div1 as well! Congratulations to [user:Errichto,2020-11-15], your knapsack is ready for a journey to win! - 0:04. [user:Sho10,2020-11-15] first to solve Div2B. Well done! - 0:05. We also have the first question. So far so good... - 0:06. [user:Um_nik,2020-11-15] gets the first pretests pass in Div1B. The cheaters are caught! - 0:09. [user:bandiaoz,2020-11-15] packs the first Knapsack in Div2! A difficulty spike is coming... - 0:12....
Let $DP[i][j]$ be the maximum similarity score if we end the first, 1. $A_i$ and $B_j$ are the same letters. In this case, we say that $DP[i][j] = min(DP[i][j], DP[i-1, 2. In every case, we can refer to $DP[i][j-1]$ or $DP[i][j-1]$ to extend one of the previous

Full text and comments »

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

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

Full text and comments »

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

39.
By Phantasmagorias, history, 5 years ago, In English
Codeforces Round #745 Editorial I'm very sorry about all the inconvenience, and I would like to bear the blame. Much thanks to those who help me prepare this round. It's not their fault. And much thanks to your participation. [problem:1581A] ------------------ idea: [user:interlude,2021-09-30] preparation: [user:CQXYM,2021-09-30] tutorial: [user:CQXYM,2021-09-30] Assume a permutation $p$, and $\sum_{i=2}^{2n}[p_{i-1}<p_i]=k$. Assume a permutaion $q$, satisfying $\forall 1 \leqslant i \leqslant 2n, q_i=2n-p_i$. We can know that $\forall 2 \leqslant i \leqslant 2n,[p_{i-1}<p_i]+[q_{i-1}<q_i]=1$. Thus,$\sum_{i=2}^{2n}[q_{i-1}<q_i]=2n-1-k$, and either $p$ should be counted or $q$ should be counted. All in all, the half of all the permutaions would be counted in the answer. Thus, the answer is $\frac{1}{2}(2n)!$. The time complexity is $O(\sum n)$. If you precalulate the factors, then the complexity will be $O(t+n)$. ----- <spoiler summary="solution"> ~~~~~ #include<stdio.h> int f[100001]; int m...
)); dp(n, k, 0); cout << f[0][n][k] << endl; return 0; } ~~~~~, . Define the dp state $f_{i,j}$ as the maxium answer in the subtree rooted at node $i$, and we choose $j, Define the dp state $f_{l,s,d}$ as the number of the permutaion length of $l$ with exactly $d$ such, In addition, the answer of the problem is $f_{n,m,k}$. Actually, the dp proccess is just like a, void dp(int sz, int cnt, int dep) { if (f[dep][sz][cnt] != -1) return ; register int &F

Full text and comments »

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

40.
By pajenegod, 3 years ago, In English
The Ultimate Reroot Template Hi Codeforces! Have you ever had this issue before? ![ ](https://cdn.discordapp.com/attachments/572613134020247562/1191774699110285392/image.png?ex=65a6a9ae&is=659434ae&hm=aeb62b0d97a84c226709b88bc3db7647f4509eef7c3a757a798ffe37e7e91c2b&) If yes, then you have come to the right place! This is a blog about my super easy to use template for (reroot) DP on trees. I really believe that this template is kind of revolutionary for solving reroot DP problems. I've implemented it both in [Python](https://codeforces.me/contest/1324/submission/240129139) and in [C++](https://codeforces.me/contest/1324/submission/240131453) (the template supports `Python2`, `Python3` and `>= C++14`). Using this template, you will be able to easily solve > 2000 rated reroot problems in a couple of minutes, with a couple of lines of code. A big thanks goes out to everyone that has helped me by giving feedback on blog and/or discussing reroot with me, [user:nor,2024-01-03], [user:meooow,2024-01-03], [u...
# Compute DP for root=0 DP = [0] * n bfs = [0] P = [0] * n for node in bfs, # Compute DP for root=0 DP = treeDP(0, graph, default, combine, finalize), # Use the exclusive function to reroot for node in bfs: DP[P[node]] = DP[node, (graph[node]): if P[node] != nei: nodeDP = combine(nodeDP, DP[nei], node, ) rootDP = [] edgeDP = {} for root in range(n): DP = treeDP(root, graph, default, , combine, finalize = lambda nodeDP,node,eind: nodeDP): DP = [0] * len(graph) def dfs(node, parent=-1, , default, combine, finalize = lambda nodeDP,node,eind: nodeDP): DP = [0] * len(graph) def dfs(node, The general idea behind rerooting is that we first compute the DP as normal for some arbitrary node, def treeDP(root, graph, default, combine, finalize = lambda nodeDP,node,eind: nodeDP):DP = [0, dfs(root) return DP

Full text and comments »

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

41.
By Um_nik, history, 10 years ago, In English
F.A.Q. (in PM) Q1: I'm a newbie. What should I do to become great coder? A1: <s>Stop doing competetive programming</s> Solve problems. Q2: I'm doing CP for two months and I'm still <s>not red</s> green. What should I do? A2: <s>You are lazy and impatient</s> Solve more problems. Q3: You became a red in less than two years, it is unbelievable! A3: No, it isn't. <s>You can do it too if you will solve fucking problems.</s> Q4: You became a red blah-blah-blah such a huge fan blah-blah. Oh, and what should I do to become as great as you? A4: ... right. You already know the answer. Solve problems. <s>I hate you.</s> Q5: I'm not good at DP [or something]. What can you suggest? A5. Maybe you should try to <s>stop asking stupid questions and</s> solve some problems on DP? Or read some blogs and editorials. Q6: I can't solve a problem / understand your code. Can you help me? (Well, it is not a bad question in general. It is a good (if you really want me to explain something not...
Q5: I'm not good at DP [or something]. What can you suggest? A5. Maybe you should try tostop

Full text and comments »

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

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

Full text and comments »

43.
By awoo, history, 6 years ago, translation, In English
Educational Codeforces Round 104 Editorial [problem:1487A] Idea: [user:BledDest,2021-02-16] <spoiler summary="Tutorial"> [tutorial:1487A] </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<int> a(n); for (int& x : a) cin >> x; cout << n - count(a.begin(), a.end(), *min_element(a.begin(), a.end())) << endl; } } ~~~~~ </spoiler> [problem:1487B] Idea: [user:adedalic,2021-02-16] <spoiler summary="Tutorial"> [tutorial:1487B] </spoiler> <spoiler summary="Solution (adedalic)"> ~~~~~ fun main() { repeat(readLine()!!.toInt()) { var (n, k) = readLine()!!.split(' ').map { it.toInt() } k-- val floor = n / 2 println((k + (n % 2) * k / floor) % n + 1) } } ~~~~~ </spoiler> [problem:1487C] Idea: [user:BledDest,2021-02-16] <spoiler summary="Tutorial"> [tutorial:1487C] </spoiler> <spoiler...
(val < 0 && digit != 0) --ncarry; if (digit == s[i] - '0') dp[1][ncarry + M][cp][cn] = min

Full text and comments »

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

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

Full text and comments »

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

45.
By Radewoosh, history, 7 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...
Let's look at [this](https://codeforces.me/contest/932/problem/F) problem. It is about someDP on

Full text and comments »

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

46.
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> ...
>= l) x = last - l + 1; ans += a[r / i] * x; } return ans; } ll dp[N][17]; void yo(int, { return s2[r][l]; } return ans; } ll dp[N][17]; int32_t main() { ios_base, ~~~~~ #include using namespace std;, const int N = 1e5 + 9, mod = 998244353; vector v[2]; int dp[2][N]; int a[N]; int32_t main

Full text and comments »

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

47.
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...
some subset DP (see? small=important) to calculate needed values.

Full text and comments »

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

48.
By gnudgnaoh, history, 5 years ago, In English
Digit DP "tricks" Prereq: [this digit dp blog](https://codeforces.me/blog/entry/53960) Cut the flag dimension ------------------------- Usually, whatever states you use in the recursive dp function, you will memoize it. And often you will have some thing like this ~~~~~ int memo[pos][...][...][low] ~~~~~ Where `low` is the flag that checks if the current number is already smaller than the considered number. It is totally possible to subtract this dimension (half the memory needed) by manipulating it in the recursive function: Example problem: [Perfect Number](https://codeforces.me/contest/919/problem/B) This is what "normal" code would look like: <spoiler summary="normal code"> ~~~~~ ll mem[20][11][2]; ll dp(int pos, int sum, bool lo) { if(sum > 10) return 0; if(pos == n) return (sum == 10); ll& res = mem[pos][sum][lo]; if(res != -1) return res; res = 0; int mx = lo ? 9 : v[pos]; for(int d = 0; d <= mx; d++) ...
Digit DP "tricks", ### Another way of digit dp From [this stackoverflow question](https://stackoverflow.com/questions, **This is an extremely important optimization for digit dp**, Feel free to share any tricks or anything that people should know when doing digit dp! If there is, For many numbers, instead of having a state for the remainder for each number, eg: `dp[...][rem2, If you want to check divisibility by 5, the last digit need to be 0 or 5. For 10, the lastdigit, Prereq: [this digit dp blog](https://codeforces.me/blog/entry/53960), You might notice that we're always doing dp from the most significant digit to the least, usually, You might wonder, "but how? you are doing dp many times on many different numbers!". Well actually

Full text and comments »

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

49.
By sugim48, 8 years ago, In English
[AtCoder] Educational DP Contest <p style='font-size: large; color:red;'> <strong>The contest was postponed to <a href='https://www.timeanddate.com/worldclock/fixedtime.html?iso=20190106T11&ah=5'>2019-01-06(Sun) 11:00-16:00 UTC</a>.</strong> </p> Hello, Codeforces! We will hold **[Educational DP Contest](https://atcoder.jp/contests/dp)** at AtCoder on Saturday. #### About the Contest This is an unofficial contest to practice **DP (Dynamic Programming)**. We selected 26 DPs, mostly basic ones, and prepared a problem to learn each of them. Test your skills during the real contest, and brush them up after it ends. #### Details - Time (YY-MM-DD): [2019-01-06(Sun) 11:00-16:00 UTC](https://www.timeanddate.com/worldclock/fixedtime.html?iso=20190106T11&ah=5) (<strong>postponed</strong>) - Duration: 5 hours - Number of Tasks: 26 - Point Values: 100 points each - Rated: No #### Rules [The rules for ABC, ARC and AGC](https://atcoder.jp/contests/dp/rule) apply. The important points are: - This ...
[AtCoder] Educational DP Contest, This is an unofficial contest to practice **DP (Dynamic Programming)**. We selected 26 DPs, mostly, We will hold **[Educational DP Contest](https://atcoder.jp/contests/dp)** at AtCoder on Saturday., [The rules for ABC, ARC and AGC](https://atcoder.jp/contests/dp/rule) apply. The important points

Full text and comments »

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

50.
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; ...
[i]; totA+=a[i]; totB+=b[i]; } dp[0][0]=true; for (int i=1;i<=N;i++){ for, int N,K; int a[505],b[505]; bool dp[505][505]; //number of shrubs considered, "extra" red

Full text and comments »

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

51.
By Arpa, history, 10 years ago, In English
Codeforces Round #383 editorial Hello again, and hope you have been Joon-Joon of the round :P **I’m preparing harder version of some of the problems (Div.2 A, B, and Div.1 A, D) and I’ll put them on some gym, so if you are interested in harder version of problems please wait for about one week.** You can see and download the problem archives (pretests, **tests**, statements, validator, checker, **solutions**) [here](https://mega.nz/#F!GoB1gCjK!fE_6d5qSSiqt_HMxAmV9GQ). You can see solutions in solutions folder, note that there are several codes there, there is a descriptor for each code (.desc) that shows the verdict of that code. Preparation details: -------------------- On 25 May [user:Sa1378,2016-12-06] came up with problem Div.1 D and other problems authored inchmeal. 9/25/16: Proposal sent to Gleb. 11/12/16: Answer from Gleb: Your proposal has been redirected to Nikolay [user:KAN,2017-06-02]. 11/15/16: Nikolay has replied, and commented about problems, saying some problems are easy, s...
**Div.2 A**: Write the last digit of $1378^n$ for several small values.

Full text and comments »

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

52.
By shadow9236, history, 3 years ago, In English
A different implementation of digit DP problems Hello Codeforces,<br> Digit dp was one of the techniques which I had the hardest time trying to learn. I have seen multiple blogs on iterative digit dp. In this blog, I would like to share my recursive implementation of digit dp. <h1>Problem Structure</h1> Typically, digit dp is used in problems of finding the number of values in a range $[l,r]$ which follow a certain property. Let us call this $f(l,r)$. The following method will work only when $f(l,r) = f(0,r) - f(0,l-1)$, which is true for most of the problems. We will now focus on how to calculate $g(n) = f(0,n)$. <h1>Idea behind the algorithm</h1> To count all numbers less than or equal to $n$ which follow a certain property, we first count all numbers with the same number of digits as $n$. Here the numerical order will be the same as lexicographical order. We can now iterate over the common prefix of the two numbers and the first character which differs after the prefix. This gives us the following template. ```c...
A different implementation of digit DP problems, ```cpp const int N = 40; int dp[N+5][10*N + 5]; // dp[i][j, Hello Codeforces, Digit dp was one of the techniques which I had the hardest time trying to

Full text and comments »

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

53.
By UnexpectedValue, 4 years ago, In English
CSES DP Section Editorial (Part 2) While looking up an editorial for a CSES task, I recently stumbled upon [CSES DP Section editorial](https://codeforces.me/blog/entry/70018) blog by [user:icecuber,2023-02-07]. Noticing that a few new tasks had been added since the blog was posted 2 years back; I decided to take his permission and write this blog, which contains editorials to the newly added tasks and acts as a sequel to his blog. I would like to thank [user:dominique38,2023-02-10] for being the most enthusiastic co-author possible, [user:defnotmee,2023-04-29] for being the second most enthusiastic co-author (he wanted the title himself), [user:Perpetually_Purple,2023-02-10] for helping me out and giving suggestions, [user:AntennaeVY,2023-02-10] for suggestions on the understandability and formatting of the blog; and finally, [user:icecuber,2023-02-10] himself for going over the blog and giving me confidence in the form of a final thumbs-up! The editorials may at some point appear excessively lengthy, but that is...
CSES DP Section Editorial (Part 2), fixing that the current digit will be $d$. We will increase our dp by $dp [n-1][d][lz'][tight']$, where, given integer $c$. Let the number of digits in $c$ be $n$. Let us define our dp state as $dp[n, This problem is a very standard application of **Digit DP**. Digit DP can be used to solve problems, dp state to now be $dp[n][x] =$ number of valid integers with $n$ digits whose leadingdigit is

Full text and comments »

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

54.
By theoneandonlytron, history, 6 weeks ago, In English
Dp Digit # This blog is my personal reflection on what I have learned in Dp Digit ## Theory - Dp digit template is something like this: ```cpp ll dfs(pos, tight, [some conditions], target) if pos == target: return something if (current_state != -1) return current_state limit = if tight = true --> target[pos] else 9 (may vary depending on problem) for i : 0 --> limit: update_tight() answ += do something() dp[pos][tight][some condition] = answ return answ ``` ## Trick 1. $$\text{Answ}(L,R)=\text{Answ}(0,R)-\text{Answ}(0,L)$$ 2. If you dp digit allow the numbers to move around, fix the segment `l - r` its goona be in making it much easier ## Ideas ### [Gym 100886 G](https://codeforces.me/gym/100886/problem/G) - this problem mentioned max, which mean you can't use trick 1 - so we must keep a `low_tight` for keeping the number `>= L`, and a `high_tight` to keep a number `<= R` - and then you just keep max nu...
Dp Digit, ## Theory - Dp digit template is something like this:, - Not really dp digit because contain a lot of combinatorics but it contain dp digit idea - so, - very fun problem indeed, instead of normal dp digit, we use the tight logic again - consider `dp, 2. If you dp digit allow the numbers to move around, fix the segment `l - r` its goona be in making

Full text and comments »

55.
By rembocoder, 4 years ago, translation, In English
Simple DP optimizations No, I don't mean Convex Hull Trick and Knuth optimization. I mean simpler and more common methods. _This is a continuation of my series of posts on DP, to understand the terminology read the [prologue](https://codeforces.me/blog/entry/102542)._ ### Transitions from a segment Very often after building the DP graph one can discover that the transitions into a state go not from a random set of vertices, but from some segment of values for one of the parameters. _For example, from states `dp[i][j]` with some constant `i` and `j` lying in a segment `[a, b]`._ **In such cases one may not implement each transition separately, but to implement them all at once.** If by implementing a transition we mean adding from `dp[A]` to `dp[B]`, then we can use prefix sums. In case if we need to find the _best_ transition into `dp[B]`, then we can use Segment Tree. #### An Example [AtCoder DP Contest: Problem M](https://atcoder.jp/contests/dp/tasks/dp_m) _Find the number of integer seq...
Simple DP optimizations, count `dp[i][j]` in `O(1)`., ), c(n); for (int i = 0; i < n; i++) { cin >> t[i] >> c[i]; } vector dp, .** If by implementing a transition we mean adding from `dp[A]` to `dp[B]`, then we can use prefix, ; vector a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } vector dp(k, But let's consider from which states there is a transition into the state `dp [i][j][k]`. If the, Let's consider where the states into`dp[i][j]` are leading from. **Obviously, from `dp[i - 1][l, Let's have a closer look on where the transitions from the state `dp[i][j][k]` are leading to: in, The value of DP will be the largest sum of values of the picked objects for the given state of the, The value of DP will be the minimal total price of the picked products for a given state of the, The value of DP will be the smallest sum of all weights of the picked objects for the given state, The value of `dp[i][j][k]` will be the number of paths of the process leading into this state., The value of `dp[i][j]` will be the number of paths of the process leading into this state., Very often after building the DP graph one can discover that the transitions into a state go not, [AtCoder DP Contest: Problem E](https://atcoder.jp/contests/dp/tasks/dp_e) _There are `n` objects, [AtCoder DP Contest: Problem M](https://atcoder.jp/contests/dp/tasks/dp_m) _Find the number of, ]; } vector> dp(m + 1, vector(b + 1)); // current layer dp[0][0] = 1; for (int i, _This is a continuation of my series of posts on DP, to understand the terminology read the, dp(max_v + 1, 2e18); // if there are no paths leading to that state, the minimal sum is

Full text and comments »

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

56.
By Geothermal, history, 7 years ago, In English
AtCoder Beginner Contest 135 English Solutions #A &mdash; Harmony Without loss of generality, let $A < B$. Then, we have three cases: - $K$ is less than $A$. This gives $A - K = B - K$, which gives $A = B$, which is false. - $K$ is greater than $B$. This gives $K - A = K - B$, which is also false. - $K$ is between $A$ and $B$. This gives $K - A = B - K$, which gives $2K = A+B$. Thus, we must have $2K=A+B$. If $A+B$ is odd, there is thus no solution. If $A+B$ is even, our answer is $\frac{A+B}{2}$. It is easy to verify that this number is indeed between $A$ and $B$. Runtime: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc135/submissions/6560205) --- #B &mdash; 0 or 1 Swap Let $K$ be the number of positions $i$ at which $p_i \neq i$ (using 1-indexing). If $K = 0$, the answer is yes, as we can simply leave the permutation as is. If $K = 2$, the answer is also yes: swap the two misplaced elements. (Notice that we can never have $K = 1$, as if any element is put in the wrong posi...
Let $dp[i][j]$ be the number of ways to create an $i$-digit number consistent with the first $i

Full text and comments »

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

57.
By oolimry, history, 6 years ago, In English
Codeforces Raif Round 1 Editorial [problem:1428A] ------------------ Setter: [user:bensonlzl,2020-10-17] Prepared by: [user:errorgorn,2020-10-17] <spoiler summary="Hint 1"> Consider when $x_1=x_2$ </spoiler> <spoiler summary="Hint 2"> Consider when $x_1 \ne x_2$ </spoiler> <spoiler summary="Solution"> We consider 2 cases. The first is that the starting and ending point lie on an axis-aligned line. In this case, we simply pull the box in 1 direction, and the time needed is the distance between the 2 points as we need 1 second to decrease the distance by 1. The second is that they do not lie on any axis-aligned line. Wabbit can pull the box horizontally (left or right depends on the relative values of $x_1$ and $x_2$) for $|x_1-x_2|$ seconds, take 2 seconds to move either above or below the box, then take another $|y_1-y_2|$ seconds to move the box to $(x_2,y_2)$. </spoiler> <spoiler summary="Code (C++)"> ```c++ #include <bits/stdc++.h> using namespace std; int main(){ ios_base::...
digit separately. Then, we can update the dp table by considering all possible transitions for all

Full text and comments »

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

58.
By Xellos, history, 11 years ago, In English
Codeforces Round #333 — editorial ### Hints: [div2A](#div2A): Try conversions between bases. [div2B](#div2B): Solve a simpler version of the problem where $A_{i+1} \neq A_i$ for all $i$. [div1A](#div1A): What are the shortest paths of the vehicles? what's the shorter of those paths? [div1B](#div1B): Forget about the ceiling function. Draw points $(i,A[i])$ and lines between them &mdash; what's the Lipschitz constant geometrically? [div1C](#div1C): Some dynamic programming. Definitely not for the exp. score of one person &mdash; look at fixed scores instead. [div1D](#div1D): Compute $dif(v)$ in $O(N)$ (without hashing) and then solve the problem in $O(N^2)$. You need some smart merges. [div1E](#div1E): Can you solve the problem without events of type 1 or 2? Also, how about solving it offline &mdash; as queries on subsets. ![ ](https://i.imgur.com/bnWmD60.png) ### <a name="div2A"></a>Div. 2 A: Two Bases ------------------------------------ It's easy to compare two numbers if the same bas...
After some attempts, one finds out that there's no reasonable way to make a DP for an expected rank, This takes $O(m^{2}n^2)$ time, since there are $O(mn)$ scores, $O(mn^2)$ states of theDP and

Full text and comments »

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

59.
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...
From $dp(total,r)=l$, we can extend $r$, transitioning to $dp (total+w_{r+1},r+1)$ or $dp(total,r+1, Furthermore, $can$ is monotone on the dimension $r$, so $dp(total,r) \leq dp (total,r+1)$., However, it would only make sense to transition to $dp(total-w_{l'},r)=l'$ for $ dp(total,r-1) \leq, Then our transition would be $dp(i,j)=\max\limits_{0 \leq k \leq K_i}(dp (i-1,j-k\cdot W_i)+k\cdot

Full text and comments »

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

60.
By Endagorion, history, 9 years ago, In English
Yandex.Algorithm 2017, third elimination round: editorial (with challenges, bells and whistles) This time I've decided to play with spoilers to faciliate the presentation as some of the guys here did before. Tell me what you think about this write-up! #### Problem A. Shifts Topics: dynamic programming. Summary: the first "hard" problem of the contest. Knowing your basic DP problems helps a lot, but coming up with the precisely correct solution may take a lot of persistence. Solution: Suppose that we are allowed to make left circular shifts as well as right ones. <spoiler summary="Can you solve the problem in this case?"> First of all, making a shift is effectively moving a character to a different position in the string. Clearly, moving a character more than once makes no sense since we could have just moved it to its final destination instead without wasting any operations. Also, it obvious that the number of occurences of each character should be the same in both strings since it is preserved by shifts. Now, consider the characters that are *not* moved by ...
We may proceed over digits of $n$ until we meet a digit $d, have a chance to match the first digit. However, we cannot tell right away if the firstdigit can be, Solution: Since we aim to maximize the number, let us look what is the largest firstdigit we can

Full text and comments »

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

61.
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; ...
- 1]; } } vector> dp(n + 1, vector(n + 1)); vector

Full text and comments »

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

62.
By darkshadows, history, 11 years ago, In English
DP on Trees Tutorial A certain question on Quora and some junior asking about DP on Trees is what inspired this post. Its been a long time since I wrote any tutorial, so, its a welcome break from monotonicity of events. Pre-requisites: - Will to read this post thoroughly. :) - Also, you should know basic dynamic programming, the optimal substructure property and memoisation. - Trees(basic DFS, subtree definition, children etc.) Dynamic Programming(DP) is a technique to solve problems by breaking them down into overlapping sub-problems which follow the optimal substructure. We all know of various problems using DP like subset sum, knapsack, coin change etc. We can also use DP on trees to solve some specific problems. We define functions for nodes of the trees, which we calculate recursively based on children of a nodes. One of the states in our DP usually is a node $i$, denoting that we are solving for the subtree of node $i$. As we do examples, things will get clear for you. ...
DP on Trees Tutorial, define our state as $\textrm{dp}(i)$ denoting answer for $A_1, A_2, ..., A_i$. Now, we define our, to root the tree first. Say, if we root the tree at node $1$ and define our DP $\textrm{dp}(V)$ as, Dynamic Programming(DP) is a technique to solve problems by breaking them down into overlapping sub, Now, how do we decide which node in $T1$ is mapped to which in $T2$. Again, we useDP here. We, So, we can write a recursion by defining maximum of two cases. $\textrm{dp}(V) = \textrm{max, That's the end of it. Now time for some person advice :) The more you practice DP/DP on trees, the

Full text and comments »

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

63.
By Jon.Snow, 7 years ago, In English
DIGIT DP Tutorial [ITERATIVE] #### Why iterative? I learned digit DP few years back but only recently I realised that the recursive solution is sometimes hard to debug and difficult to reason about. So this article aims to provide an iterative solution template that can be extended to solve similar problems. Problem Statement ------------------ Find count of numbers in range [L, R] such that sum of its digits is a prime number.<br> - $1 <= L,R <= 10^{18}$ Basic Idea ------------------ - A brute force approach would be to iterate through each number from L to R and check if sum of its digits is prime. This will obviously timeout as constraints are too large. - So which particular property can we count such that we don't consume too much time/memory? <br> Sum of digits of numbers! **Sum of digits of a number cannot exceed 180** for 18 digits, thus we will have to track only 180 states which will save time and memory.This is the key idea behind most digit DP problems: identify and track a proper...
DIGIT DP Tutorial [ITERATIVE], $dp[0][..][..]$ which denotes the entire input string, $dp[i][0][sum] \rightarrow$ count of suffixes that can be formed starting from index, #### Why iterative? I learned digit DP few years back but only recently I realised that the, - **Base Cases** `dp[n][0][0] = dp[n][1][0] = 1` There exists $1$ empty suffix with sum of, - Educational Codeforces Digit DP problem: https://codeforces.me/contest/1036/problem/C, //count of all numbers in [0,ss] which have prime sum of digits //dp [i][tight][sum] => number of, For every state of dp we also need to know if the current suffix formed includes all unbounded, digit DP problems: identify and track a property which is finite and will help us reach the answer., ~~~~~ dp[20][2][200] ~~~~~ 20 $\rightarrow$ maximum number of

Full text and comments »

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

64.
By kartik8800, history, 6 years ago, In English
Introduction to Digit Dynamic Programming Hello Codeforces! This series of videos are focused on explaining dynamic programming by illustrating the application of digit DP through the use of selected problems from platforms like Codeforces, Codechef, SPOJ, CSES and Atcoder. After going through this series, you should find yourself confident in solving problems which require the use of digit dp and also implementing them in a reasonable amount of time. I will also live code and submit the solutions to the problem on the coding platform from where the problem comes. Some Basic elements of Dynamic Programming ------------------ Some general ideas and my thoughts about DP to help you get started:<br> Part 1: [https://youtu.be/24hk2qW_BCU](https://youtu.be/24hk2qW_BCU)<br> 1. What is Divide and Conquer?<br> 2. What is Dynamic Programming?<br> 3. Types of DP problems.<br> Part 2: [https://youtu.be/yfgKw6BUZUk](https://youtu.be/yfgKw6BUZUk)<br> 1. What is a DP-state?<br> 2. Characterizing a DP-state.<br>...
Introduction to Digit Dynamic Programming, 1. What exactly is Digit DP? 2. What are the types of problems I can solve with Digit DP?, Introduction to Digit DP ------------------

Full text and comments »

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

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

Full text and comments »

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

66.
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 ...
$$ \text{dp[at][msk] = dp[at - 1][msk] * poss[at][0] + dp[at - 1][msk ^ mask[at]] * poss[at][1]} $$, $$ \text{dp[at][msk] = dp[at - 1][msk] + dp[at - 1][msk ^ mask[at]]} $$, dp[at][msk] += dp[at - 1][msk ^ mask[at]] * 1LL * poss[at][1] % MOD; dp [at][msk] %= MOD; }

Full text and comments »

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

67.
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...
signed main(){ ios::sync_with_stdio(false); cin.tie(); cout.tie(); dp[0] = dp[1

Full text and comments »

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

68.
By flying_saucer, 9 months ago, In English
Iterative Digit DP (A bit simpler approach) ## 1. What is Digit DP? Digit DP is a technique used to compute information such as counts or sums of numbers within a range `[l, r]`, when the constraint depends on the digits of the number. Here, the bounds can be very large (up to $10^{18}$ or larger). Instead of solving the range directly, we reduce the problem to: <br><br> $$ Answer(l, r) = F(r + 1) - F(l) $$ where `F(n)` computes the required information for all numbers in the range `[0, n)`. Thus, the main task becomes implementing a function `F(n)`. Although Digit DP is often presented recursively, an iterative formulation is usually easier to debug and understand once the idea is clear. This article describes the iterative viewpoint. --- ## 2. Core Idea to implement the function F(n) To make this work cleanly, we represent all integers using the same number of digits by allowing leading zeros. Additionally, we prepend one extra leading zero to every integer so that the most significant digit is a...
Iterative Digit DP (A bit simpler approach), ## 1. What is Digit DP?

Full text and comments »

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

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

Full text and comments »

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

70.
By awoo, history, 6 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...
forn(i, N) forn(j, N) dp[i][j] = -INF; dp[0][0] = 0; forn(i, n) forn(j, N) if ( dp[i][j] >= 0, memset(dp, -1, sizeof(dp)); dp[0][0] = 0; forn(i, sz(siz)) forn(j, N) if (dp [i][j] != -1

Full text and comments »

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

71.
By Proofy, 15 months ago, In English
[Tutorial] Abstract Proofs of DP Algorithms ## Introduction Most of DP algorithms I studied online, there are some subtleties that I didn't find any proof of. May be they are found somewhere already, but not to my knowledge. I think most people find the things that I'm going to prove here intuitive and need no proof, but for if you're really picky about being uncertain of something if you didn't see a proof (like me), it can bother you. Also, knowing the proofs can sometimes better help the thinking process. The purpose of this blog is to provide examples of proofs of famous DP algorithms to, first show them, and second serve as a general pattern of techniques on how would one prove a DP algorithm. Now, most DP problem involve a set of states $V$, and a set of transitions $E$ such that $(V, E)$ constitutes a directed acyclic graph or DAG (sometimes weighted). Thus, we will continue discussing DP calculations on a DAG. ### Conventions - A graph $G = (V, E)$ is a pair of sets $V$ and $E$ where $E \subseteq ...
[Tutorial] Abstract Proofs of DP Algorithms, Now, the transitions are the standard Digit DP transitions:

Full text and comments »

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

72.
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...
## 3.1 A O(n) DP-algorithm for greedy labeling. In the case of the greedy labeling, it is possible

Full text and comments »

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

73.
By errorgorn, 5 years ago, In English
Generalized FWHT: How I realized I did not understand FWHT I would like to preface this blog by saying this is not a tutorial on FWHT but some (maybe obvious) observations on FWHT that I wanted to share. Thanks to [user:rama_pang,2021-10-15] and [user:oolimry,2021-10-15] for proof reading. Love you guys <3 Of course I (and the proof-readers) are not perfect so if you find anything unclear just tell me in the comments. ![ ](https://cdn.discordapp.com/attachments/752406106009239585/898378522899402772/unknown.png) We will use the symbols $\\&,|,\oplus$ to represent bitwise and, bitwise or, bitwise xor respectively. ## FWHT Given $2$ arrays $A$ and $B$. We will want to find array $C$ such that $C_i=\sum\limits_{j \star k=i} A_j \cdot B_k$. For our normal FFT, the operation $\star$ is just addition. When finding fast for FFT, I found library code that does FWHT $^{[1]}$, that is it does the above operation where $\star$ can also be any of the $3$ bitwise operations. We focus on the case for $\oplus$. We focus even more spe...

Full text and comments »

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

74.
By neal, 6 years ago, In English
Unofficial Editorial for Educational Round 94 (Div. 2) Haven't done one of these for a while! Here are my approaches to the problems: #### [problem:1400A] We just need to make sure our string of $n$ characters matches each of the $n$ substrings in at least one spot. The easiest way to do this is to take every other character from $s$. Code: [submission:90908018] Another fun solution: we can generate random strings and check them until we find one that matches everything. This works because the probability of failing to match any particular substring is $\frac{1}{2^n}$, so as $n$ gets bigger the probability of failing gets extremely low. Code: [submission:90999219] #### [problem:1400B] First iterate on the number of swords we will personally take. Then we should greedily take as many war axes as we can until we run out of money. At this point, our follower needs to take as many items as possible. They can do this by greedily taking whichever of swords or war axes are cheaper until they run out, followed by taking the more expensi...
then do a DP for each component where dp(mask, k) = the number of submasks of mask that have k ones and

Full text and comments »

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

75.
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...
dp[i][1][0] = min(dp[i][1][0], min(dp[i - 1][0][0], dp[i - 1][0][1]) + 1); dp [i][1][1] = min(dp

Full text and comments »

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

76.
By RDDCCD, history, 4 years ago, In English
Editorial of CodeTON Round 4 (Div. 1 + Div. 2, Rated, Prizes!) [A. Beautiful Sequence](https://codeforces.me/contest/1810/problem/A) <spoiler summary="Hint"> What is the necessary and sufficient condition? </spoiler> <spoiler summary="Tutorial"> The necessary and sufficient condition for a beautiful sequence is that there exist one $i$, such that $a_{i} \le i$. Just check the sequence for the condition. </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; int a[100005]; void solve() { int n; scanf("%d",&n); for(int i =1;i <= n;i++) scanf("%d",&a[i]); for(int i = 1;i <= n;i++) { if(a[i] <= i) { puts("YES"); return; } } puts("NO"); } int main() { int t;scanf("%d",&t); while(t--) solve(); } ~~~~~ </spoiler> [B. Candies](https://codeforces.me/contest/1810/problem/B) <spoiler summary="Hint"> How the binary representation changes after an operation? </spoiler> <spoiler summary="Tutorial"...
So, the operation is just insert a $0/1$ before the last digit. And the answer for an odd $n$ is

Full text and comments »

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

77.
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...
int main() { cin>>N>>MOD; precompute(); dp[0][0]=1; for (int i=0;i

Full text and comments »

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

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

Full text and comments »

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

79.
By THE_THUNDERSTORM_BEGINS, history, 14 months ago, In English
DP overview this blog will talk about the info needed to solve DP problems in general. DP or dynamic programming is a method used to solve bigger problems be dividing them in some way however while learning DP i recommend being similar with some data structures , sometimes we might just need a set or a map but at expert level i recommend being familiar with segment tree data structure. this blog will be divided into phases where i explain some basic DP problems or explain some DP method in general. each phase will contain codes and examples , you can ask more questions in comments. 1.Fibonacci ------------------ sorry for this i really know this is what people tend to explain when doing DP but hear me out the standard Fibonacci function looked something like this ``` int f(int n){ if(n<1)return 0; return f(n-1)+f(n-2); } ``` thinking about the complexity of this code , it appears that if takes $O(f(n))$ time complexity. you should know that $f(40)=1023341...
DP overview, 12.digit DP ------------------

Full text and comments »

80.
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...
Because every digit is large, every two digits being added together will carry to the nextdigit

Full text and comments »

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