Блог пользователя peltorator

Автор peltorator, 3 дня назад, По-английски

Most of you have probably heard of $$$\omega$$$, the matrix multiplication exponent. Are you sure you fully understand its definition, though? I thought so too, until I started asking myself some uncomfortable questions and realized that I had some subtle misconceptions. To answer these questions, I read a bunch of papers and book chapters, and now I have some peace of mind. Let me try to scare you a bit first and then hopefully rebuild your understanding of fast matrix multiplication.

Let's start with four questions. Try to answer them before reading further.

Q1: Does there exist an $$$O(n^{\omega})$$$-time matrix multiplication algorithm?

Q2: Does there exist an $$$o(n^{\omega})$$$-time matrix multiplication algorithm?

Q3: Does there exist an $$$O(n^{\omega + 0.1})$$$-time algorithm for integer matrix multiplication?

Q4: Does there exist an $$$O(n^{\omega - 0.1})$$$-time algorithm for integer matrix multiplication?

Answers

If you had asked me a month ago, I would have been quite surprised by these answers. Now let's take a closer look at the matrix multiplication exponent and make sense of these answers.

But first: what is $$$\omega$$$? Intuitively, it should be something along the lines of "the smallest value $$$t$$$ such that $$$n \times n$$$ matrices can be multiplied in time $$$O(n^t)$$$". From this definition, the answer to the first question should clearly be "yes". However, the definition is not quite right because the relevant set of exponents may not have a minimum. The correct definition takes the infimum over all valid exponents.

There could be no single "best" matrix multiplication algorithm, but only a sequence of better and better ones. As a result, the definition only guarantees algorithms running in time $$$O(n^{\omega + \varepsilon})$$$ for every fixed $$$\varepsilon \gt 0$$$. It does not tell us whether the infimum is actually attained. So Q1 is not true by definition. It might be true, but we simply don't know.

This is why statements like "using fast matrix multiplication we solve the problem in $$$O(n^{\omega})$$$ time" are not very precise. Even though before this journey I knew that $$$\omega$$$ is an infimum and not a minimum, I never stopped to think through what that really implies. If you want a notation for an actual achievable running time, writing something like $$$\mathrm{MM}(n, n, n)$$$ is cleaner. Here we mean that we can plug in the time complexity of any specific matrix multiplication algorithm.

Time complexities of the form $$$O(n^{\omega} \cdot \log n)$$$ make even less sense. What people usually mean is that the algorithm performs $$$O(\log n)$$$ matrix multiplications, plus some lower-order work. But we are measuring small logarithmic factors while being imprecise about a much larger polynomial factor. Once you write the bound as $$$O(n^{\omega + \varepsilon} \log n)$$$, the extra $$$\log n$$$ can be absorbed into a slightly larger exponent, so this is still just $$$O(n^{\omega + \varepsilon'})$$$ for every $$$\varepsilon' \gt 0$$$.

This brings us to the second question. Even if there is a single "best" algorithm, its running time need not be exactly $$$\Theta(n^\omega)$$$. It could be $$$O(n^\omega \log n)$$$, or even $$$O(n^\omega / \log n)$$$, which is $$$o(n^\omega)$$$. Of course, the second possibility can only happen if $$$\omega \gt 2$$$, since reading the input already takes $$$\Theta(n^2)$$$ time. But until we prove that $$$\omega = 2$$$, an $$$o(n^\omega)$$$-time algorithm cannot be ruled out.

Surprisingly, we are not done yet. Given our current definition of $$$\omega$$$, the third question sounds trivial. If there is an algorithm working in time $$$O(n^{\omega + \varepsilon})$$$ for every $$$\varepsilon \gt 0$$$, we can in particular take $$$\varepsilon = 0.1$$$, right? In reality, our definition of $$$\omega$$$ is still not precise. What exact problem are we solving? What does "matrix multiplication" mean? Is it boolean matrix multiplication? Integer? Real? In what model of computation are we counting the time complexity? Turns out, $$$\omega$$$ only counts the shortest sequence of arithmetic operations computing the product of two $$$n \times n$$$ matrices. Note that the size of this sequence may depend on the set of values from which the matrix entries are taken. In other words, we need to fix the underlying field. It could be $$$\mathbb{R}$$$, $$$\mathbb{Q}$$$, $$$\mathbb{F}_p$$$, or any other one. Each specific field gives its own matrix multiplication exponent: $$$\omega(\mathbb{R})$$$, $$$\omega(\mathbb{Q})$$$, $$$\omega(\mathbb{F}_p)$$$. And when people just say $$$\omega$$$, they (most likely) mean the most general case that we normally care about: $$$\omega(\mathbb{R})$$$.

This poses two problems for us. First, there may exist a sequence of $$$O(n^{\omega + \varepsilon})$$$ arithmetic operations that computes the matrix product, but is there an actual algorithm that knows what operations to do in what order? Note that we need to know this sequence for each of the infinitely many values of $$$n$$$. Second, even if we know the list of operations, it may very well include arbitrary real numbers like $$$\sqrt{2}$$$ or $$$\pi$$$. It could be problematic for us to perform these computations exactly in our standard computational model (for example, word-RAM). Even if we use floating point numbers, we may have precision issues due to subtractions and divisions.

Let us now resolve these two issues. The first one is the easier one. Suppose we know how to multiply $$$k \times k$$$ matrices optimally for some constant $$$k$$$. Then we can use the idea behind Strassen's algorithm (the first and simplest algorithm that solves matrix multiplication in time $$$O(n^{3 - \varepsilon})$$$) to get a relatively good algorithm for arbitrarily large matrices. We split an $$$n \times n$$$ matrix into a $$$k \times k$$$ grid of blocks of size roughly $$$(n / k) \times (n / k)$$$ each and apply the scheme recursively on the blocks. It is not hard to show that by picking $$$k$$$ large enough, we can achieve time complexity $$$O(n^{\omega + \varepsilon})$$$ for any fixed $$$\varepsilon \gt 0$$$. This is pretty neat: we have no idea what the value of $$$\omega$$$ is, but we know that Strassen-like algorithms achieve almost-optimal time complexity regardless.

The harder issue is getting rid of arbitrary real coefficients. This takes a lot of work that goes beyond the scope of this blog post, but the gist is as follows. The matrix exponent is not too sensitive to the specific field at hand, and in particular $$$\omega(\mathbb{R}) = \omega(\mathbb{Q})$$$. (If you want a precise statement, one can prove that $$$\omega$$$ only depends on the field characteristic.) Therefore, in the algorithm described above, it is sufficient to consider only sequences of arithmetic operations for $$$k \times k$$$ matrices using rational coefficients. That's a big relief! Once the coefficients are rational, we can reduce the whole computation modulo some suitable prime $$$p$$$. The prime should just not divide any coefficient denominators and should be large enough that the exact integer answer can be recovered from the result modulo $$$p$$$. (Technically, this is still not enough if divisions are allowed as arithmetic operations, but once again, one can prove that we only need additions, subtractions, and multiplications.) This algorithm can now be easily implemented in $$$O(n^{\omega + \varepsilon})$$$ time on a word-RAM.

So the answer to the third question is indeed "yes". But not for a trivial definitional reason; it relies on several nontrivial facts connecting algebraic complexity over fields to actual algorithms over integers.

Finally, we move to the fourth question. The definition of $$$\omega$$$ lives in the algebraic world: it is about arithmetic complexity over $$$\mathbb{R}$$$. There is no obvious reason why the optimal word-RAM complexity of integer matrix multiplication has to match that exponent. In principle, it may be easier. So we cannot rule out an $$$O(n^{\omega - 0.1})$$$-time algorithm for integer matrix multiplication. (Of course, assuming that $$$\omega \ge 2.1$$$.)

If this blog post challenged your mental model of $$$\omega$$$, I am happy. Hopefully, you now have a more accurate one. As a final exercise, try to prove that there exists an $$$O(n^{\omega + o(1)})$$$-time algorithm for matrix multiplication. This is stronger than having an $$$O(n^{\omega + \varepsilon})$$$-time algorithm for every fixed $$$\varepsilon \gt 0$$$.

Solution sketch

Полный текст и комментарии »

  • Проголосовать: нравится
  • +359
  • Проголосовать: не нравится

Автор peltorator, 10 месяцев назад, По-английски

Hi!

We’re continuing our deep dive into FFT! Check out the stream series announcement blog post for more details. Tomorrow, Thursday, June 19th, 2025 at 14:00 UTC, I will be streaming an intermediate-level lecture on my YouTube channel.

We'll explore how to make the basic FFT implementation more than 10x faster, how to solve more advanced problems with it, what NTT is, and plenty of other cool tricks along the way. This stream is mainly aimed at participants rated 1900–2000+ on Codeforces, but anyone interested is welcome to join.

Note: This isn’t a sequential lecture series. This particular stream is designed for people who already learned FFT a while ago, have solved a few problems with it, and are now looking to deepen their understanding and learn how to apply it to harder problems.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +116
  • Проголосовать: не нравится

Автор peltorator, 11 месяцев назад, По-английски

Hi Codeforces!

I’ve long believed that it's really worth revisiting the same competitive programming topics multiple times. The first time, you’re just trying to survive and maybe grasp the basics. The second time, you’ve solved some problems, you know where you got confused, and you're ready to absorb more. By the third time, you’ve seen and solved enough to start appreciating the subtleties — the tricks, advanced applications, deeper meaning. But most lectures I’ve seen are designed as a one-size-fits-all — trying to cover everything from scratch and dive into the advanced stuff in one go. That’s rarely optimal.

Take binary search. I once talked about it for six hours straight. A beginner at that lecture would’ve probably quit CP immediately. And that’s ok. Beginners don’t need all that. But the truth is, there is that much depth to explore even in seemingly simple topics like binary search — once you're ready. Yet many people only see the beginner version once and move on. Their understanding stays stuck at that level forever.

FFT is another great example. Almost every FFT lecture I’ve seen tries to do everything in one sitting: start from zero and end with "you now know everything there is to know about FFT and all its applications". But FFT is big, it’s hard. It makes more sense to have:

  • A basic lecture: just enough to multiply polynomials with minimal pain.

  • An intermediate one: assume you know the basics, and dive deeper.

  • And maybe an advanced one: weird tricks, optimizations, cool use cases.

There are many more topics like that: segment trees, square root decomposition, MSTs, etc.

So I’m starting an irregular stream series called "Algorithms in Depth". Each topic will be split by level:

  • Beginner: minimum viable understanding to start solving problems.

  • Intermediate: expanding the basic understanding to solve harder problems.

  • Advanced: deep understanding, fun tricks, and higher-level abstractions.

Most lectures try to combine the beginner and intermediate levels and skip the advanced part completely. I want to keep these levels separate — to not overwhelm beginners, bore intermediates, or neglect the advanced participants. I'm starting with Fast Fourier Transform (FFT). The first stream will cover only the basics. No fancy math. Just the simplest path to fast polynomial multiplication. As much motivation and intuition as possible. If you know what a polynomial is and how to multiply them by hand, you're good to go.

The stream will happen on my youtube channel on Thursday, May 29, 2025 at 14:00 UTC. Everyone’s welcome — ask questions in chat, and the recording will be available afterward. Hope to see you there!

Полный текст и комментарии »

  • Проголосовать: нравится
  • +631
  • Проголосовать: не нравится

Автор peltorator, 16 месяцев назад, По-английски

Hi!

Last time I wrote a contest, I got RE1 on a submission that worked on my computer, and you helped me figure out what was wrong. This time I have an even weirder situation. I have CE on a submission that works on my computer. I don't know what's wrong with me. I guess it's a combination of being stupid and being extremely unlucky.

So here is the submission for problem F: 299683526. I submitted it ~10 mins before the end of the contest and got CE. The CE message says something about std::vector but I don't really understand how it is connected to my program. I tried to change some things and even submit with C++23 but it didn't help. After the end of the contest, I learned that a friend of mine had the same issue with problem E. He was able to fix it by submitting with C++17. I then tried to run my code in the "custom invocation" codeforces tab with C++17, and indeed it compiles and works as expected. As my friend had the same problem, this seems to be a bit concerning. Is everything ok with C++20 and C++23 compilers on Codeforces?

Полный текст и комментарии »

  • Проголосовать: нравится
  • +24
  • Проголосовать: не нравится

Автор peltorator, 16 месяцев назад, По-английски

Codeforces Global Round 28 just finished, and I had a heartbreaking moment. Three minutes before the end of the contest, I finished writing code for problem G, submitted it, and got RE1. I didn't have enough time to figure out what the problem was. However, after the contest, I was able to understand what causes this behavior but I still can't figure out WHY this happens so maybe some C++ experts among you can help me :)

Submission for reference: 297344731. I have a structure for modular arithmetics template<int mod> struct ModularInt. Inside it, it has a static vector of some modular inverses: static vector<ModularInt<mod>> invs; that is then initialized after the end of the structure: template<int mod> vector<ModularInt<mod>> ModularInt<mod>::invs{ModularInt<mod>{0}, ModularInt<mod>{1}};. I then use this vector of inverses in the modular inverse function:

inline ModularInt<mod> inv() const {
    assert(value != 0);
    int ans = 1;
    int curval = value;
    while (curval >= invs.size()) {
        int tmp = mod / curval;
        ans = 1LL * ans * (mod - tmp) % mod;
        curval = mod - tmp * curval;
    }
    return invs[curval] * ans;
}

For some reason on codeforces, this function causes division by zero error on line 6. It happens because invs.size() is equal to zero which clearly cannot be the case because vector invs is initialized with two elements. This error happens if I use the inverse operation to declare some global values. However, if I move these computations inside the main function, this problem disappears, and the submission gets AC (see 297350557). On my computer, I cannot replicate this problem. Could somebody please help me to understand why this is happening and how to fix it?

Полный текст и комментарии »

  • Проголосовать: нравится
  • +31
  • Проголосовать: не нравится

Автор peltorator, 21 месяц назад, По-английски

Recently at the AtCoder World Tour Finals tourist shared his latest optimal contest strategy development — the so-called "never submit" strategy: an improvement over the "late submit" strategy. You can learn more about it in the following clip from the stream:

Полный текст и комментарии »

  • Проголосовать: нравится
  • +287
  • Проголосовать: не нравится

Автор peltorator, 2 года назад, По-английски

Ranges and views from c++20 are cool. Today I have learned that C++23 brings even more fun stuff from python to c++. For example, zip and enumerate. These are some of the features from python that I missed the most in c++. Also, now there is a thing called cartesian product which helps one to avoid writing 5 nested loops.

I think these things could be pretty handy for competitive programming, so I would like to ask: what other features of c++23 do you find interesting? And when do you think we could get c++23 on Codeforces?

Полный текст и комментарии »

  • Проголосовать: нравится
  • +47
  • Проголосовать: не нравится

Автор peltorator, 2 года назад, По-английски

I was waiting for somebody to post this, but I guess I am going to post it for history purposes. Here is the clip:

https://youtube.com/clip/UgkxjClduTG6kL6s3c8BFNNYdE1HVR2wGMxf?si=pFZCy3KapKbTLNCC

They cut it out pretty quickly in the broadcast, but let me tell you what we were seeing from the audience. The team of KNU is coming to the stage. They all have some kinds of pins on their T-shirts with Ukrainian flags. In the clip, you can see it if you pause and look closely. But they switch the camera away quickly. Then the team members and the coach go behind the big screens. Normally other teams go out on the stage pretty quickly, but here nothing is happening for like a minute. Then they walk onto the stage, with no pins anymore. I don't know what happened behind these screens, but it probably isn't hard to make an educated guess. For context: clip from EUC.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +66
  • Проголосовать: не нравится

Автор peltorator, 2 года назад, По-английски

Today, the European Championship was held in Prague. The first of its kind. And it was... the worst organized contest I have ever participated in. This is not only sad in isolation but also especially sad as the contest itself (the problems) was actually nice, and I would like to thank the authors for that!

So what was so bad about it?

Let me describe how entering the contest works. One first goes to the cloakroom. Then, one proceeds via a long corridor to another building, where in a relatively small space, all teams gather for half an hour. Then, "id check" begins. I mean... I have never seen this before but in itself, there is nothing wrong with it. They want to check your identity. Makes sense. However, what do you think would be a reasonable way to do it? I would think that one and only reasonable way to do it is the following: one comes to the entrance of the contest area, a volunteer checks their id and matches with their badge, and the contestant comes in. As you could have already guessed, it was not like that. The system works in the following way: you wait aimlessly for half an hour in this relatively tight space, and then they start calling teams one by one in random order. They check the ids of the team they call, and then this team goes further. To the contest area? No no no! To a different tight space where teams slowly gather, and then, after 20 more minutes teams are allowed to go to the contest area. This system literally makes zero sense and does not take into account the interests of participants in any way or form. I felt like organizers think about us like amazon thinks about its goods. Just transport them in the way they want regardless of how much these items need to wait at random spots because amazon products don't have feelings. But to the surprise of EUC organizers... participants have! And then the cherry on the top of this: again for no reason, this process was repeated twice: one day at the dress rehearsal and then the next day at the actual contest. If there was any reason to do it during the dress rehearsal, it could've been to understand that it is an awful system that should be abandoned. But no.

Ok, great! We are in the contest area. Suffering finished, right? Oh no! People put their stuff on the tables and are ready to go to the bathrooms? Huh! "You are not allowed to go to the bathroom before the contest starts". Excuse me? At first, I honestly thought it was a joke. It reminded me of some soviet-minded teachers we had at school. What is that even supposed to mean? Especially considering the fact that this conversation is happening 5 meters away from the toilet. You just kept us for like half an hour in a random tight place with no toilets and now when we arrive to the contest area, we cannot even go to the bathroom? We should wait until the contest starts and then waste our contest time? Is there any reason for that? Hard to believe.

Can't go to the toilet? Oh, maybe I can grab an additional bottle of water because for some reason there are three bottles at the workplace but one of them is sparkling? Oh no! Again. You can only take water when the contest starts. Genuinely. Are these rules there just to have rules?

Well, nevermind, sure, the contest started. What is happening? Volunteers just standing behind your back staring at your screen and loudly talking to each other. Sure... But not only that, no people in the contest area could provide any help to you regarding anything (in terms of guidance). During the dress rehearsals, we were given this transparent file which is supposed to hold a single piece of paper and we were told to leave ALL the things we will need at the actual contest inside this file. For example, food, pens, medication, three team reference materials 25 pages each already inside a larger protective case. Reasonable, right? Can I ask anybody in the contest area about WTH I am supposed to do about it? No! Because nobody knows anything. You are supposed to ask this kind of question in the system. Surely, it is so convenient to assess this kind of situation virtually.

Ok, let's come back to the actual contest. We are sitting in a place that is not made for spending prolonged periods of time there. I don't know what these things are called but it is like an atrium. So the ceiling is glass. At first, it is very cold. Surely, the organizers told you to wear the ICPC T-shirt? Well... You're gonna be freezing. Then... Surprise-surprise: the sun comes out. And it becomes insanely warm. For some, it shines directly into your eyes. For others, into the screen, and they cannot see anything. Clearly, absolutely unpredictable conditions, right? Then it becomes insanely cold again, then hot, and some more times throughout the contest. Magical experience. Loved it.

I would like to point out one red line that goes throughout these stories: random rules that should be followed just... because. I know that ICPC contests overall love random rules just to have rules. But this one... This one was pure fun. As a final rule that comes out of nowhere: link, link2.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +316
  • Проголосовать: не нравится

Автор peltorator, 2 года назад, По-английски

I decided to learn some C++20, and now I am trying to incorporate for loops with std::ranges or std::views stuff. I stumbled upon the fact that there are two options: ranges::iota_view and views::iota. They seem equivalent to me, but I wonder whether I am missing something. On the internet, I found a mention of ranges::iota_view being better than views::iota "in terms of performance", but I was not able to reproduce it. On the other hand, views::iota seems shorter and easier to alias: one can just write const auto &range = views::iota; and use Python-like for loops, but const auto &range = ranges::iota_view; wouldn't compile. One could instead use using range = ranges::iota_view<int, int>;, but this now works only for integers (adding template<typename T> to using would force me to always write range<int, int>() because apparently using in C++ does not support argument deduction). I would like to hear your opinion on this. Has anybody thought about the same question before? What did you do?

P.S. I am asking about purely competitive programming usage, not software engineering.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +11
  • Проголосовать: не нравится

Автор peltorator, 3 года назад, По-английски

The last two Div. 1 + Div. 2 rounds were not numbered:

In total, in 2023 there were already 7 such "unnumbered" rounds out of 21 rated for Div. 1. Honestly, it completely messes up the folder names on my computer. And I don't really understand why it should be so. There are numbered rounds. There is a separate numbering system for educational rounds. This is ok — two different numbering systems is no problem (like ABC, ARC, and AGC on AtCoder). Then we have Global Rounds. Then we have things like Hello, Good Bye, and April 1st rounds. Already quite a lot of instances but it is still ok, these are understandable regular things. But nowadays we have all these company-sponsored rounds that previously were just normally named rounds (and maybe had the company name added but they still were numbered as normal rounds). Why are they now also separate instances every time? Sometimes I can't even easily understand whether a round is rated or not by just looking at its name. For example, "Harbour.Space Scholarship Contest 2023-2024" does not look rated to me. And if Pinely Round 2 at least makes sense (even though I don't like the fact that we have so many small separate instances), this round name does not make sense to me at all. What is going to happen next year if there is going to be a similar contest? "Harbour.Space Scholarship Contest 2024-2025"? It becomes too messy! Why not just "Harbour.Space Scholarship Codeforces Round 895" or something like that?

Полный текст и комментарии »

  • Проголосовать: нравится
  • +105
  • Проголосовать: не нравится

Автор peltorator, 3 года назад, По-английски

One and a half months ago I proposed a challenge to every one of you to get something from your drafts or from your head and actually write a blog post about it. I got a bunch of submissions, and you can find the links to all of them throughout this blog post (I was actually surprised that all entries were meaningful and interesting, so I definitely recommend checking them out). If you submitted an entry and I didn't mention it here, it is not purposeful! Indicate it via a direct message and I will include it here. It was just a bit hard to keep track of all submissions.

I went through all the submissions. Some of them were very complicated, and I tried my best to get the overall idea but I will need to come back to dive deeper into some technical proofs. However, I believe that these technicalities that I glanced through do not affect my decisions. We are ready to present the winners!

Regarding the first place, there was no doubt in my head. Without any hesitations, I give it to Monogon with his blog post about priority-queue-like undoings on data structures. It ticked all the boxes I wanted from this challenge. It is a novel idea that is pretty easy to understand and implement at the same time. The explanation is clear and concise. I highly recommend everybody who is at least orange read it. So congratulations to Monogon. The $300 prize is yours!

Thanks to rafaelgo we also have a prize of $50 for second place. And this decision was much harder to make. In the end, it came down to two candidates:

  1. First is adamant with his blog post on online FFT and its generalization. I am a big fan of FFT, generating functions, and similar algebraic viewpoints on combinatorial problems. For me even the online FFT part was new, and even though it was already explained somewhere before, I enjoyed the explanation and the examples. And the generalization just looks like magic even though you understand that "yeah, should work I guess". Definitely not a beginner FFT material though!

  2. Second is ko_osaga with his series of blog posts on range longest increasing subsequence queries. It's based on a research paper (with the author of which I actually had an opportunity to work on the related algebraic structure of LIS a couple of years ago but I decided to not do it, maybe I should have...), and hats off to ko_osaga for simplifying and codeforcesifying it. It is fascinating that such a classical simple problem can be viewed from a very different perspective, and tools you wouldn't expect to see arise. I wouldn't lie, I was not yet able to understand everything there, but I got the main ideas. Again, please, don't try to read it if you want to learn LIS. Come back 5 years later.

It was a hard decision but I decided to go with the first one as the topic resonated more with me, and at the end of the day if there are two great ideas, why not go with the one that is easier to understand and implement? :) Congratulations to adamant on the second place! Nevertheless, congratulations to ko_osaga for the third place.

I will contact the first two winners shortly and send them their prizes. (UPD: done)

And now the list of all other entries in no particular order:

  • CMS trick by Dragonado. I was happy to see a submission from a purple user. Was sad that there weren't many. Interesting idea, I always like it when two segment trees communicate with each other.
  • Convex optimization blog series by chromate00. And blue ones too, right? Math is not as scary as you think it is.
  • On variations of string matching by brunomont. There are many different techniques for string matching. Nice to collect them all together. The wildcards one was new to me.
  • Centroid decomposition for very sparse graphs by dimss. Simple and at the same time not obvious idea.
  • FFT tutorial by -is-this-fft-. Solid tutorial with a good problem selection. I just didn't find any novel ways to explain stuff there for it to be great. Nevertheless, if you want to learn FFT, it is a place to go to.
  • Simulated annealing by qwerty787788. External blog with cool animations. More of an exploratory approach to a simple idea that is not that easy to make work properly.
  • Sometimes it's not their fault by Lyde. The only non-algorithmic entry in this challenge. I think what I got from this blog is that if I like a contest, I should write a comment about it.
  • Push-Free Segment Tree by nikgaevoy. The main idea is pretty simple. I also used it sometimes. But the applications for the 2D case were novel to me. Good stuff.
  • Two more blogs by adamant. I decided to not count them towards the win of the entry on FFT because it was a competition of blog posts, not people. The first one on permutation "basis" was very clear and not-too-mathy. The second one as I promised I did not really read into details yet. It is a continuation of a blog from 8 months ago that I also did not yet read. Looks scary and interesting.

Thank you for your attention. Arm Ukraine!

Полный текст и комментарии »

  • Проголосовать: нравится
  • +358
  • Проголосовать: не нравится

Автор peltorator, 3 года назад, По-английски

C++ is an excellent language for competitive programming, and most of the top performers use it. However, it has many flaws. Lately, Rust is getting increasingly more popular on CodeForces. I haven't yet written a single program in Rust in my entire life, however from what I have heard about it, I feel like there is actually a possibility that in 15 years it will be the most popular CP programming language as now is C++ and as 15 years ago was Pascal (don't quote me on that).

So this Saturday, January 21st at 11:00 AM UTC I will be streaming and trying to solve a CodeForces round using Rust, learning it along the way and seeking help from viewers. Additionally, we will be raising money for a great non-profit organization that helps Ukraine. More details at the beginning of the stream.

The link to the stream.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +149
  • Проголосовать: не нравится

Автор peltorator, 3 года назад, По-английски

TL;DR: Write an interesting CodeForces blog post until February 15th and win $300.

UPD: Second place will receive $50.

UPD2: Competition is over, The results are available here.

I am a huge fan of CodeForces and specifically CodeForces blog posts! There are tens and hundreds of gems posted on this platform throughout the years. Thankfully, recently there was added the catalog page where a lot of cool articles can be found. Personally, if I want to remember some classical algorithm, I would go to websites like cp-algorithms, but CodeForces is the place where new or rare stuff is born, where new points of view emerge. I think it is one of the most valuable functions of this website, and I would like to facilitate its growth. I know that many people have cool ideas in their minds that they came up with or maybe something that is known only in their community on a spoken basis, and they were always too lazy to share it with the world :) Now it is time!

That's why I am proposing the "Codeforces Month of Blog Posts", and I encourage everybody to participate. The rules are simple:

  • Post something on CodeForces no earlier than January 1st (00:01 UTC) 2023;

  • Send me a link to your blog post as a direct message on CodeForces before February 15th (23:59 UTC) 2023, and indicate that you are participating. I also recommend you post a link to your blog post in the comments here if you feel like it.

I would appreciate it if you also include a one-sentence explanation at the beginning of your blog post explaining this challenge and a link to the blog post you are reading right now so that more people can learn about it and participate, but it is not obligatory in any way, I am not forcing you to do so.

And the juicy part is: at the end of this 1.5-month period I will choose the winners, and the first place will receive a prize of $300 from me! And also thanks to rafaelgo we will be able to reward the second place with a $50 prize. But I hope you all understand that money is just a little motivation for you and the point of this is not money per se but fun.

Your blog post may be about anything you want but let me explain what I expect. As I said at the beginning, I love new ideas. So I would enjoy seeing blog posts that either introduce some cool new/rare algorithm/idea, a new interesting point of view on an already known algorithm, simplification of a classical complicated algorithm, some CP-related fascinating math construction, novel way of stress testing, etc. I think you get the point. Just create some unique piece of content related in any way to competitive programming.

I am excited to see all your amazing blog posts! Don't hesitate to share your thoughts in the comments. I am open to any suggestions. Maybe, you think that 1.5 months is not enough for you, and you want the deadline to be extended? Maybe, I didn't specify something precisely in the description of the challenge? Maybe, you would like to increase the prize fund and join the jury? Ask it in the comments or direct messages!

I wish you all a happy peaceful New Year. And talking about peace, I would like to remind you that there is a war going on in Europe right now. Ukraine is bravely standing against Russian aggression, and it needs your support. There is an uncountable number of ways you may help: both with money and your time. I will just list a couple of trusted volunteer organizations: https://wfu.world/en/, https://u24.gov.ua/, https://rassvet.world/en/sunrise/.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +579
  • Проголосовать: не нравится

Автор peltorator, 4 года назад, По-английски

UPD: schedule, list of guests, and questions form for guests added.

UPD2: link to the stream: https://youtu.be/WZKOdorb1Dg

I know that lots of you were saying that Codeforces should stay out of politics when there were lots of blog posts supporting Ukraine a couple of weeks ago. Well, I respect your opinion, but I can't agree. If you see a binary search tutorial on the "Top" page, do you complain about it if you're not interested in binary search, or do you just ignore it? And at the end of the day, it's not really about politics, but about people's lives.

Having said that, I'd like to invite you to join my 8-hour long live stream on YouTube against the Russian invasion of Ukraine next Sunday (27th of March) from 10 AM till 6 PM Ukrainian time (be careful, 27th of March is a daylight saving start in Ukraine and a lot of other countries, but it may not be the case for your country, so check your timezone using this link).

Сurrent plan is (all time periods are in Ukrainian timezone; if you want to ask questions, go here):

10:00-10:30 — Intro, tricky interesting problems for chat

10:30-11:00 — Interview with Matt tehqin Fontaine (author of Algorithms Live! youtube channel)

11:00-11:30 — Solving problems blindfolded

11:30-12:00 — Interview with Nikita nika-skybytska Skybytskyi (author of Nikita Skybytskyi youtube channel)

12:00-13:00 — Lecture: Everything I know about lambda optimisation (aliens trick)

13:00-13:30 — Interview with Alex Um_nik Danilyuk (ICPC 2020 champion team member, author of umnik_team youtube channel)

13:30-14:30 — Solving problems blindfolded

14:30-15:00 — Interview with Kamil Errichto Debowski (author of Errichto and Errichto2 youtube channels)

15:00-15:20 — Lunch break

15:20-16:00 — Cool little algorithms nobody talks about

16:00-16:30 — Interview with Anton antontrygubO_o Trygub

16:30-16:45 — Talking to chat

16:45-17:15 — Interview with Jay Geothermal Leeds (author of Jay Leeds (Geothermal) youtube channel)

17:15-17:45 — Interview with Ildar 300iq Gainullin (IOI 2019 2nd place)

17:45-18:00 — Outro

And during this stream, I'd like viewers to donate money to Ukraine. Here I'd like to get some help from you. Please, leave some organizations that help Ukraine to which we could donate money in the comments. Also, I'd like to have a counter on the stream that says how much money was donated by the viewers, but I don't understand how it is possible if they will not be donating it to me. If you know how to do it, also suggest your ideas. Of course, it's possible to donate the money to me, and then at the end of the stream I could send them to charity organizations, but first of all, you should 100% trust me in this case, and second of all, I'm a Russian citizen, so it's really hard for me to have any kind of PayPal, etc at the moment to collect money :)

If you are my friend or anyone who would like to be a guest on this stream, please DM me on Codeforces or Telegram. Don't be shy! If you have any ideas on what I should do during this stream, also write them in the comments.

Hope I'll see you in a week! NO WAR!

Полный текст и комментарии »

  • Проголосовать: нравится
  • +464
  • Проголосовать: не нравится

Автор peltorator, 4 года назад, По-русски
  • Проголосовать: нравится
  • +24
  • Проголосовать: не нравится

Автор peltorator, 4 года назад, По-английски

I really like good blog posts. And that's the main reason I like Codeforces. But as we all know, it's hard to find good blog posts here. So let's help each other and share our favorite posts, which were uploaded to Codeforces in the last year! I will share my top 10, and I encourage you to share some of your favorites in the comments.

10. Heuristic algorithm for Hamiltonian path in directed graphs by heuristica

An absolutely incredible algorithm which kinda sometimes solves the Hamiltonian path problem on some random and special kind of graphs.

9. I compiled a list of almost all useful blogs ever published on Codeforces by parveen1981

This blog has a purpose that's similar to the purpose of the blog you're reading right now. A great source of interesting blog posts!

8. Fast modular multiplication by orz

Some really interesting algorithms that help multiply 64-bit numbers modulo without int128.

7. Competitive Programming Hall of Fame — cphof.org by Ra16bit

A new awesome resource, that collects all the different achievements of CP-legends.

6. The Ultimate Topic List and (The Ultimate) Code Library by YouKn0wWho

These are two different posts, but I would like to combine them. This is a really nice collection of materials and implementations of tons of different algorithms and data structures needed for competitive programming.

5. My opinion on how to practice competitive programming by Radewoosh

Some really interesting thoughts from Radewoosh and a really long and engaging discussion in the comments.

4. C++20 Is Released by MikeMirzayanov

The main treasure of this blog post is the comments! So many interesting tricks and tips for C++20.

3. [Tutorial] GCC Optimization Pragmas by nor

I never used pragmas because I didn't understand what they're doing. Finally, there is a resource where I can close this gap in my education :)

2. Lambda optimization certificate by never_giveup

A really interesting discussion about an algorithm which is around for 5 years but still isn't really understood by the public. I learned a lot from this blog post and after that started researching a lot of things about lambda optimization (a.k.a. Lagrange optimization a.k.a. aliens trick) on my own and figured out that I didn't really understand a thing about it before.

1. [Tutorial] Li Chao Tree Extended by rama_pang

In my opinion, it is the best blog post and the best new data structure of the year. It's absolutely incredible and simple at the same time.

I hope you learned something new today. I'm looking forward to reading your favorite blogs. Merry Christmas and Happy New Year.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +210
  • Проголосовать: не нравится

Автор peltorator, 4 года назад, По-русски

Recently, there've been at least two blogs that were called "petitions". I have no idea why people use this exact word in this context but for me, it seems... overly posh. So this blog is a petition to stop calling every suggestion a petition.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +36
  • Проголосовать: не нравится

Автор peltorator, 5 лет назад, По-английски

Hi!

I wanted to make a new fun screencast. In this video, I'm solving Codeforces Round #747 (div. 2) but there are two main differences from a regular screencast:

  1. It's a highlight video which means that it's not a 2-hour long video of me thinking about problems but just some fun, interesting, exciting moments.

  2. It's something I called a "Challenge Screencast" which means that there is a challenge I need to complete during the contest. This time the challenge was to not use any loops in the code. So no for loops, no while loops... At all!

https://youtu.be/imGdtb_lB_U

I hope you'll enjoy it! I'll be happy to hear any comments and suggestions for the future challenge screencasts!

Полный текст и комментарии »

  • Проголосовать: нравится
  • +220
  • Проголосовать: не нравится

Автор peltorator, 5 лет назад, По-русски

В мае я уже рассказывал про то, что я занимаюсь созданием нового ресурса для изучения сложных алгоритмов и структур данных для спортивного программирования, о которых сложно где-то найти информацию (особенно на русском языке), и не только. Тогда он был доступен только в формате pdf-документа, что, очевидно, не всегда является наиболее удобным способом потребления информации. Но теперь после длительных страданий я все таки смог переделать все это в формат сайта, который теперь доступен по адресу peltorator.ru. Если вам удобнее пользоваться pdf-версией, не переживайте, она все еще будет обновляться параллельно с сайтом.

Теперь мне не нужно больше так много страдать с вебом, так что новые статьи будут совсем скоро :)

Буду рад любым замечаниям, предложениям и помощи:

  • Как можно улучшить интерфейс сайта
  • Какие есть ошибки и опечатки в текстах статей
  • Если вы хотите помочь мне в написании какой-то статьи на неизвестную тему, в которой вы разбираетесь, я буду рад
  • Если вы знаете какую-то неизвестную тему, но не хотите сами ничего делать, все равно буду рад, если вы мне сообщите о существовании этой темы: тогда я смогу ее изучить и написать статью

Обо всем этом можно писать мне в телеграме. А если вам совсем не лень, то ваши замечания можете делать в формате пул-реквестов на гитхабе проекта.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +71
  • Проголосовать: не нравится

Автор peltorator, 5 лет назад, По-русски

Всем привет!

Начинается новый учебный год, вместе с ним стартует и сезон олимпиад. Этот пост будет полезен школьникам, которые хотят заниматься олимпиадным программированием, но не знают где.

Сейчас открыт отбор в кружок по олимпиадному программированию «Тинькофф Поколение». Один из классных плюсов кружка — он абсолютно бесплатный, но нужно написать вступительный контест, который открыт до 12 сентября включительно. Зарегистрироваться и начать решать можно здесь: algocode.ru.

Ниже мы постараемся подробнее описать как все устроено в кружке. Если у вас останутся вопросы, задать их можно в комментариях к посту или в telegram (внизу есть наши контакты).

Каждый год мы стараемся быть лучше и действительно полезными, так что в этом году кружок будет еще интереснее.

Про формат занятий

По результатам отборочного контеста мы разделим участников на учебные параллели. У каждой параллели есть своя группа преподавателей, которые будут читать лекции, помогать с решением задач и написанием кода. Их всегда можно будет попросить объяснить непонятную тему, подсказать тест или найти ошибку в программе.

В начале занятия проводится разбор предыдущих туров: тематического и дистанционного. Далее идет лекция или семинар (а иногда и то, и другое). На лекциях преподаватели рассказывают новые алгоритмы, а на семинарах школьники сдают задачи с листочка преподавателям, и по ходу занятия задачи разбираются.

После каждого занятия будут опубликованы тематические туры на пройденную тему. Кроме тематических туров, каждую неделю будут выдаваться дистанционные туры к различным этапам Всероссийской олимпиады школьников по информатике:

  • с сентября по декабрь — к муниципальному этапу;
  • с сентября по январь — к региональному этапу;
  • с сентября по март — к заключительному этапу.

Занятия будут проходить по субботам с 16:00 до 21:00 по московскому времени.

В прошлом году из-за пандемии мы проводили очные занятия для школьников из Москвы и онлайн для ребят, которые не могли посещать занятия очно. В этом году планируем продолжить опыт гибридных занятий: очно+online (каждый год во время анонса кружка прилетают вопросы про участие в кружке ребят из других стран. Мы будем рады всем, но нужно понимать, что основной фокус на школьников из России, и во время подготовки к олимпиадам есть своя специфика).

1. Онлайн

Мы проводим занятия для участников из всех регионов. Лекции проводятся в Zoom. Занятия проводят преподаватели, которые также очно преподают в московском кружке и принимают участие в подготовке олимпиад и проведении сборов. Это возможность заниматься на равне со школьниками из крупных городов.

2. Очно

Очные занятия проходят в Штаб-квартире Тинькофф

Если наберется, достаточное количество участников, мы готовы проводить занятия очно в Центре Разработки Тинькофф в Санкт-Петербурге по адресу:

Описание параллелей

Параллель А

Параллель рассчитана на опытных олимпиадников: участников и дипломантов Всероссийской олимпиады по информатике прошлого года. Научим решать сверхсложные и нетипичные задачи.

Преподаватели: Филипп grphil Грибов и Егор peltorator Горбачев

Примеры тем:

  • Нетривиальные алгоритмы и задачи теории чисел.
  • Декомпозиции деревьев: centroid, heavy-light, ladder.
  • Задачи на графах: паросочетания, остовы и их применение в задачах.
  • Продвинутые структуры данных: неявные деревья отрезков, двумерные структуры, персистентные структуры, segment tree beats.
  • Корневая декомпозиция.
  • Быстрое преобразование Фурье.
  • Строковые структуры данных: Ахо-Корасик, суффиксный массив, суффиксный автомат.
  • Алгоритмы поиска потоков в сетях, алгоритмы поиска минимальных глобальных разрезов.
  • Продвинутые геометрические алгоритмы: вращающийся scanline, пересечение полуплоскостей, диаграмма Вороного, триангуляция Делоне.
  • Splay-деревья, link-cut.
  • Нетривиальные алгоритмы на графах: венгерский алгоритм, алгоритм двух китайцев, дерево доминаторов.
  • Матроиды.
  • Алгоритмы во внешней памяти.
  • И многое-многое другое...

Параллель A'

Для опытных олимпиадников — участников финала Всероса по информатике, Открытой олимпиады и других перечневых олимпиад.

Преподаватели: Иван isaf27 Сафонов, Константин KiKoS Амеличев и Дмитрий _overrated_ Умнов.

Примеры тем:

  • Структуры данных: от дерева отрезков до splay-дерева.
  • Оптимизации динамического программирования: convex hull trick, meet-in-the-middle, разделяй и властвуй
  • Декомпозиции деревьев: centroid, heavy-light, ladder.
  • Задачи на графах: паросочетания, потоки, dinamic connectivity problem.
  • Геометрия: выпуклые оболочки, сумма Минковского.
  • Строки: хэши, Ахо-Корасик, суффиксный массив.
  • Полезные трюки: STL, битовые оптимизации, стресс-тестирование.

Параллель B

Для тех, кто владеет С++ или Java и уверенно проходит на региональный этап Всероса.

Преподаватели: Максим DebNatkh Деб Натх, Артем SoMuchDrama Рябов, Игорь Siberian Маркелов.

Примеры тем:

  • Графы: BFS, DFS, их применения. Алгоритмы поиска кратчайших путей во взвешенных графах (алгоритмы Форда — Беллмана, Дейкстры и Флойда). Минимальные остовные деревья. Паросочетания, алгоритм Куна.
  • Деревья: алгоритм поиска наименьшего общего предка в дереве. Эйлеров обход. Декомпозиции дерева (heavy-light, centroid).
  • Строки: префикс-функция, Z-функция, бор, автомат Ахо-Корасик, хеширование, суффиксный массив.
  • Динамическое программирование: одномерное, многомерное; по подмаскам, подграфам, подотрезкам, подмножествам, профилю и изломанному профилю.
  • Структуры данных: дерево отрезков с массовыми операциями, декартово дерево, sparse table, система непересекающихся множеств, дерево Фенвика.
  • Геометрия: базовые примитивы, алгоритмы построения выпуклой оболочки, построение касательной к выпуклому многоугольнику.
  • И много других тем: теория Шпрага-Гранди, корневая декомпозиция, метод разделяй и властвуй, решето Эратосфена, задача дискретного логарифмирования, meet-in-the-middle.

Параллель B'

Для тех, кто на базовом уровне владеет С++, Python или Java и участвовал в муниципальном этапе Всероссийской олимпиады школьников по информатике прошлого года.

Преподаватели: Глеб Glebodin Лобанов, Александр rationalex Гришутин и Андрей forestryks Одинцов.

Примеры тем:

  • C++ с нуля.
  • Структуры данных: система непересекающихся множеств, sparse table, дерево отрезков.
  • Динамическое программирования: от самых базовых задач до динамики по подстрокам, подмножествам и цифрам.
  • Алгоритмы на графах: от обходов графа до поиска мостов, точек сочленения, построения минимального остововного дерева.
  • Алгоритмы на деревьях: LCA, LA, эйлеров обход.
  • Базовые алгоритмы на строках: префикс-функция, Z-функция, хеши и бор.
  • Геометрия: от векторов и прямых до многоугольников и выпуклой оболочки.

Параллель C

Параллель рассчитана на школьников, которые никогда не занимались олимпиадным программированием или неуверенно себя чувствуют в базовых темах и хотят познакомиться с ними поближе. Необходимо знать синтаксис любого языка программирования и уметь решать простейшие задачи по математике и программированию. В эту параллель не зачисляются школьники, которые перешли в 11 класс.

Преподаватели: Егор w8_m8 Гутров и Полина Romanchenko Романченко.

Примеры тем:

  • C++ с нуля.
  • Сортировки: квадратичные, сортировка слиянием, быстрая сортировка.
  • Бинарный поиск: обычный и по ответу.
  • Теория чисел: алгоритм Евклида, разбиение числа на простые.
  • Простейшие структуры данных: vector, set, map, стек, очередь, дек.
  • Базовое динамическое программирование: с нуля до задач о рюкзаке, НВП, НОП.
  • Подсчет комбинаторных объектов.
  • Базовые алгоритмы на графах: хранение, поиск в глубину, ширину, алгоритмы Дейкстры, Флойда, Форда — Беллмана, конденсация графа.
  • Простая геометрия: векторы, прямые, окружности.

Зарегистрироваться и начать решать можно по ссылке: algocode.ru.

Другие направления

Кроме алгоритмов и структур данных у нас также есть несколько других интересных направлений: олимпиадная математика, машинное обучение и глубокое обучение.

Контакты

Если хотите узнать что-то подробнее, можете написать Тане TKolinkova Колинковой в телеграм @Tatyana_Kolinkova или на почту best-talents@tinkoff.ru.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +135
  • Проголосовать: не нравится

Автор peltorator, 5 лет назад, По-русски

Иногда я нахожу всякие прикольные штуки про спортивное программирование и связные области, и хочется поделиться этим со всем миром. Обычно в таком случае люди дают задачи на найденные трюки на своих контестах, но я задачи придумывать не умею, так что я решил просто рассказывать о них в телеграме.

Ссылка на телеграм канал

Подписывайтесь, если вам такое интересно :)

Полный текст и комментарии »

  • Проголосовать: нравится
  • +57
  • Проголосовать: не нравится

Автор peltorator, 5 лет назад, По-английски

As some of you asked me, I'd like to share a video in which I'm talking about my competitive programming setup (especially codeforces). I'm talking about my hardware, google chrome extensions for codeforces, vim setup + snippets, c++ template, and much more.

If you're interested in something specific, you may want to use timestamps in the description. All the links to everything I'm talking about in this video are in the video description.

Link to the video

Полный текст и комментарии »

  • Проголосовать: нравится
  • +106
  • Проголосовать: не нравится

Автор peltorator, 5 лет назад, По-русски

TL;DR Хочется сделать новый e-maxx с актуальными алгоритмами и удобными реализациями с упором на продвинутые алгоритмы, про которые мало где можно прочитать. Сейчас уже есть 23 статьи, собранные по ссылке: peltorator.ru/cp_book.pdf. Последние изменения доступны по ссылке. TeX исходники доступны на гитхабе. Веб-версию можно найти по сссылке peltorator.ru.

Всем привет!

Я хотел бы показать, над чем я работал последние 4 месяца. Начнем издалека. Все мы любим e-maxx, все мы им пользуемся. Однако я уверен, вы тоже чувствуете, что он не идеален. Во-первых, он уже не обновлялся 9 лет, и за это время появилась куча разных новых актуальных алгоритмов, о которых можно прочитать только в случайных статьях на codeforces и подобных сайтах, да еще и в основном только на английском языке (или китайском). Во-вторых, часто коды, которые есть на e-maxx'е, используются по принципу "я не знаю, что там написано, но оно работает, поэтому не буду трогать". Хочется все же, чтобы к статьям по возможности были приложены красивые, удобные и понятные реализации.

Такие мысли и привели меня к идее сделать в некотором смысле e-maxx 2.0. Безусловно, это очень большая работа, поэтому на это уйдет много времени, но уже сейчас я хотел бы поделиться некоторым промежуточным результатом. Чтобы это не было источником, в котором в сотый раз рассказывают, что такое DFS и BFS, я решил пойти с обратной стороны и начать с тех алгоритмов, о которых сложно найти какую-либо информацию. Тем более на русском языке. На данный момент это существует в виде LaTeX-документа, расположенного по адресу peltorator.ru/cp_book.pdf. В будущем, думаю, стоит перевести это в сайт.

А еще помимо текста там есть картиночки! Кажется, они помогают пониманию. И в конце почти каждой главы есть список задач для практики.

Также для ускорения процесса я думаю, что стоит привлечь соавторов. Пока что я собираюсь попросить своих знакомых, однако если вам это интересно, то можете написать мне в телеграме, буду рад любой помощи!

Буду очень признателен любым комментариям и пожеланиям под этим постом. Если вы нашли опечатку или тем более ошибку, то тоже обязательно сообщите мне о ней (если вам не лень), я в срочном порядке все исправлю. Актуальный документ всегда будет находиться по той же самой ссылке. Возможно, стоит создать еще страницу, на которой будут перечислены все последние важные изменения в документе.

P.S. Если вы начинающий участник соревнований по программированию, то, пожалуйста, не воспринимайте это как todo-лист. Алгоритмы, конечно, играют роль в спортивном программировании, но намного большую роль играет практика решения задач.

UPD: Теперь последние изменения документа доступны по ссылке. Также на титульной странице документа теперь написана последняя дата обновления, а следующая страница содержит полезные ссылки.

UPD2: Теперь TeX-овские исходники статей и другие материалы доступны на гитхабе.

Со списком статей, которые уже написаны, можно ознакомиться в оглавлении документа, но я также продублирую его здесь:

  1. Префиксные суммы (стандартная тема, но я попытался затронуть более продвинутые моменты, которые очевидны опытным участникам, но нигде, кажется, не прописаны)
  2. Разреженные таблицы (здесь нет особо ничего нового, эта статья нужна скорее как пререквизит к статье про disjoint sparse table, которой пока нет)
  3. Дерево отрезков снизу
  4. Segment Tree Beats
  5. RMQ offline. Вариация алгоритма Тарьяна
  6. Алгоритм Фараха-Колтона и Бендера (советую обратить внимание на конец статьи, потому что там представлен занимательный линейный алгоритм, который одновременно очень просто пишется, и при этом сильно быстрее ФКБ на практике)
  7. Дерево Ли Чао (с улучшениями: минимум кусочно-линейных функций и ленивые обновления)
  8. Двоичные подъемы с линейной памятью
  9. Персистентный Convex Hull Trick
  10. Нахождение обратных ко всем остаткам за $$$O(p)$$$ (два самых простых метода)
  11. Поиск факториала по простому модулю
  12. Поиск факториала по простому модулю за $$$O\left(\sqrt{\min(p, n)} \log n\right)$$$
  13. Обращение Мёбиуса, свертка Дирихле
  14. Квадратный корень по простому модулю за $$$O(\log p)$$$
  15. Дискретное логарифирование (+ вариация для ответа на много запросов)
  16. Преобразование Уолша-Адамара и xor-and-or-свертки, SOS-DP
  17. Рандомизированный алгоритм поиска пары ближайших точек на плоскости за $$$O(n)$$$
  18. Рандомизированный алгоритм проверки пересечения полуплоскостей на непустоту за $$$O(n)$$$
  19. Рандомизированный алгоритм поиска минимальной покрывающей окуржности множества точек на плоскости за $$$O(n)$$$
  20. Поиск пересечения полуплоскостей при условии, что известна точка внутри этого пересечения
  21. Генерация случайных чисел, и все, что с этим связано
  22. Стресс-тестирование
  23. Быстрый ввод-вывод в C++

Полный текст и комментарии »

  • Проголосовать: нравится
  • +188
  • Проголосовать: не нравится

Автор peltorator, 5 лет назад, По-английски

When you use C++ and the input is really big you can't just use cin and cout. You need to speed up it with

ios::sync_with_stdio(0);
cin.tie(0);

Someone argues that the second line is unnecessary but it's not true. if the input and output alternate then adding the second line makes I/O more than twice faster. But then... Someone argues that we also need to use cout.tie(0).

I personally never use this and I don't know any case where it can help. So my question for today is the following: "Is there any case where we actually need cout.tie? Or is it completely useless?"

Полный текст и комментарии »

  • Проголосовать: нравится
  • +276
  • Проголосовать: не нравится