Скоро Codeforces Round 1133 (Div. 1, Div. 2)! Регистрация здесь. ×

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

Автор gepardo, история, 10 лет назад, По-русски

Перед вами разбор задач сегодняшнего контеста. Я постарался расписать решения задач как можно более подробно, но если что-то будет непонятно, смело пишите в комментариях! :)

785A - Антон и многогранники

Подсказка
Разбор
Код C++
Код Java
Код Python

785B - Антон и занятия

Подсказка
Разбор
Код C++
Код Java
Код Python

785C - Антон и сказка

В этой задаче были слабые претесты. Это было сделано для того, чтобы спровоцировать побольше взломов. И да, я предупреждал в анонсе :)

Подсказка
Разбор
Код C++
Код Java
Код Python

785D - Антон и школа - 2

Подсказка
Разбор
Код C++
Код Java

785E - Антон и перестановка

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

Если у вас в этой задаче TL или ML, не стоит думать, что ограничения по времени/памяти слишком узкие. Авторское решение работает за 1.2 секунды и тратит 9 МБ памяти.

Подсказка
Разбор
Код C++
Код Java

Альтернативное решение от Vladik:

Код C++

Альтернативное решение от netman:

Код Java
Разбор задач Codeforces Round 404 (Div. 2)
  • Проголосовать: нравится
  • +186
  • Проголосовать: не нравится

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Автокомментарий: текст был обновлен пользователем gepardo (предыдущая версия, новая версия, сравнить).

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by gepardo (previous revision, new revision, compare).

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Also notice that k can be found using a formula, but such solutions could fail by accuracy, because the formula is using the square root function.

Is there any way to get the solution by formula either in c++ or python while still retaining accuracy?

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +2 Проголосовать: не нравится

785A - Anton and Polyhedrons Hint: 404 Not Found quit interesting:)

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +25 Проголосовать: не нравится

Thanks! I like the way the editorial is written :D

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +8 Проголосовать: не нравится

Wow, Great Editorial. Equality of all languages.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Если в задаче C использовать long double (C++), то точности хватает. Тест на котором не хватает double: 999999998765257152 10 (ответ 1414213572)

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +4 Проголосовать: не нравится

This editorial with hints and opening blocks! Something new and beautiful in this edutorial! I've never senn something like this!

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +9 Проголосовать: не нравится

the iterative solution of C passes in time limit ... should've taken care about that..

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +1 Проголосовать: не нравится

It is also possible to solve C using linear search: 25518550

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

salute to alex256.. this is the best editorial i've ever seen..i've always wanted to have those "hints" kind of thing

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Range tree + decard tree = O((n + q) * log n ^ 2) in problem E

  • »
    »
    10 лет назад, скрыть # ^ |
    ← Rev. 2  
    Проголосовать: нравится 0 Проголосовать: не нравится

    Можешь объяснить свою идею?

    Я пытался хранить в каждой вершине дерева отрезков декартово. При свапах я сначала удавляю элементы из соответстующих деревьев (пересчитывая инверсии в "соседних" вершинах ДО), а потом добавляю. O(n log n + q log^2 n). Но это не заходит по времени (я пытался запустить на кфе — оно на макстестах работает около 5.5 сек).

    Рисуночек с объяснением и посылка

    • »
      »
      »
      10 лет назад, скрыть # ^ |
       
      Проголосовать: нравится +5 Проголосовать: не нравится

      Мое решение за использовало похожую идею, только я хранил декартки не внутри ДО, а внутри дерева Фенвика.

      Код C++

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

      Код C++
      • »
        »
        »
        »
        10 лет назад, скрыть # ^ |
         
        Проголосовать: нравится 0 Проголосовать: не нравится

        У меня зашло и на дереве отрезков, когда я понял, что инверсии слева и справа связаны, и начал считать только одну из них. Но все равно 3.5сек: посылка.

        А еще у меня где-то там UB, видимо, потому что я ловлю WA1 на c++ 14, на котором мой прошлый код работал быстрее, чем на MSVC10.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Ошибка в разборе задачи D: "количество закрывающих скобок до данной". Правильно будет "после"

»
10 лет назад, скрыть # |
← Rev. 4  
Проголосовать: нравится +8 Проголосовать: не нравится

problem E:

— TLE

— OK 1310 ms.

(what i'm doing wrong?)

  • »
    »
    10 лет назад, скрыть # ^ |
    ← Rev. 2  
    Проголосовать: нравится 0 Проголосовать: не нравится

    I also passed with . Are you sure your solution with square root decomposition isn't actually because if it is it actually makes sense that your TLEd.

    UPD: Your solution really is .

  • »
    »
    10 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    I passed in under 2000ms when i changed to BIT from segment tree with Order statistics tree in

  • »
    »
    10 лет назад, скрыть # ^ |
     
    Проголосовать: нравится -33 Проголосовать: не нравится

    logx has a higher growth rate than sqrt(x) for larger inputs

  • »
    »
    10 лет назад, скрыть # ^ |
     
    Проголосовать: нравится +15 Проголосовать: не нравится

    I have a completely different algorithm that runs in time O(n log n + q sqrt(n)). It's here: 25590906 It is much simpler than the one in the editorial.

    Draw the permutation as a 2-D plot. The key things that you need to be able to do are to (1) count the number of points below and to the left of a query point and (2) insert and delete points into the plot.

    So we use a sqrt(n) decomposition of the plot into sqrt(n) by sqrt(n) squares of size sqrt(n). For each square we keep the number of points in it. We also keep a hierarchy of squares doubled in size. So there are .5 log n of these levels.

    To solve a query we first note that there is an ell-shaped part that is that is outside of the squares described above. These can be counted in O(sqrt(n)) time. We maintain the permutation and its inverse. So the horizontal part of the ell (and the vertical too) can be counted row by row. Now to count the number of points in the squares we peel off possibly the top row and column and just count them. Now we move into the next level of boxes that are twice as big. The total time for this count is therefore O(sqrt(n)).

    Inserting and deleting from the boxes is easy. Just make a pass through the levels. This takes O(log n) time.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +2 Проголосовать: не нравится

This is truly one of the best editorials on CF till date. Giving hints and then the complete idea to the question is a good way to help us improve ourselves. Also, giving reference code in three different languages is a very appreciable effort. Congratulations to the writers of the contest for this excellent editorial and we hope to look more such editorials in the future.

»
10 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

Can anyone help me get rid of that 1e018 in 9th test case in problem C. 25537798 There are other submissions where the same formula is used but have an AC.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

In problem C why do we have to binary search up to 2e9 not 1e9(it give WA)?Look at my submission with 1e9(25537413) and 2e9(25538410)???

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Can someone help me with the proof of — 785D — Anton and School — 2 , I am not getting the explanation given in tutorial . Thanks in advance

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Has anyone got AC in E using segment tree with multiset(supporting order stats)? I am getting TLE on #7.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Было бы очень здорово, если все авторы оформляли разбор так же, как и вы. Спасибо!

»
10 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

if problem E2 is data structures, it may be not hard to solve =))

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +15 Проголосовать: не нравится

My funny task A solution.

long sum = 0;
for (int n = nextInt(); n > 0; n--) {
    long x = -next().codePointAt(0);
    sum -= (((13 * x + 4870) * x + 662555) * x + 39072170) * x + 846175272;
}
println(sum / 33660);

Also fan fact, that all task contains test case with "404" answer.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +5 Проголосовать: не нравится

Presentation of the editorial is really amazing... I think I'd never seen that before. Thanks a lot.

»
10 лет назад, скрыть # |
← Rev. 5  
Проголосовать: нравится 0 Проголосовать: не нравится

for question E Can we have a 2D BIT where BIT[x][y] where x will denote block no and y is actual number depending on given input.Then each query is solved in sqrt(N)+log(block)*log(N) and updates also in sqrt(N)+ log(block)*log(N). Correct me if I am wrong..

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +5 Проголосовать: не нравится

Very detailed & useful tutorial. Thank you very much!

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +19 Проголосовать: не нравится

First time in my whole journey (which is albeit short), I have seen an editorialist with so much creativity and patience taking so much interest in really explaining the solutions in a comment. It's sad how whistle blogs about complaining all about this contest. More power to you, gepardo.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

D is a very nice especially if one derives it without using the identity directly! Thank you for this problem.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

I tried to solve problemE with segment tree plus ordered multisets but I am getting TLE on test 7.
The complexity of build function in my code in O(N * LOGN * LOGN * C). where C is the constant factor in segment tree.(C ≈ 4).
http://codeforces.me/contest/785/submission/25568923
Is there any way to optimize the build function.

  • »
    »
    10 лет назад, скрыть # ^ |
     
    Проголосовать: нравится +3 Проголосовать: не нравится

    What do the query1 and query2 methods do?

    • »
      »
      »
      10 лет назад, скрыть # ^ |
       
      Проголосовать: нравится 0 Проголосовать: не нравится

      query1 calculates no of elements greater than val in ranger l to r and query2 calculates no of elements less than val in ranger l to r.

      • »
        »
        »
        »
        10 лет назад, скрыть # ^ |
         
        Проголосовать: нравится 0 Проголосовать: не нравится

        These 2 values are connected.

        Suppose you have the element x in the position i in the array and you know the answer to one of the queries, e.g. there are ans elements greater than x in [1,i-1]. This necessarily means there are i-1-ans elements smaller than x in [1, i-1]. Since the total amount of elements smaller than x is x-1, there x-1-(i-1-ans) = x-i+ans elements smaller than x in [i+1, N]. Thus, the total amount of inversions is x-i+2*ANS.

        This thing should reduce the constant of your solution. Also, don't use long long everywhere — this slows down the solution, which already runs pretty close to the TL.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Is there any divMod explanations? I don't understand how it works. Thanks

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +1 Проголосовать: не нравится

Is there any divMod explanations? I don't understand how it works. Thanks

»
10 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

why is it low+m and not the midvalue+m? in 785C

»
10 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

Can Someone explain me why number of total possible valid sub sequence is x+yCx as explained in Editorial in 4th Question ? I am not able to understand that

  • »
    »
    10 лет назад, скрыть # ^ |
    ← Rev. 2  
    Проголосовать: нравится 0 Проголосовать: не нравится

    Which part of the editorial you don't understand? I'll try to explain it better.

    • »
      »
      »
      10 лет назад, скрыть # ^ |
       
      Проголосовать: нравится 0 Проголосовать: не нравится

      "At first, let's simplify the problem: let our string consists of x + y characters, begins with x characters "(" and ends with y characters ")". How to find the number of RSBS in such string?

      Let's prove that this number is equal to x+y C x.

      This is what I am not able to understand. If we take a string that consists of x + y characters, begins with x characters "(" and ends with y characters ")", then how total number of RSBS is (fact(x+y) / fact(x)*fact(y) ) ?

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

in the problem:B we have to calculate the max distance between the periods that is the time between end of first period and start of second period but in the editorial why we are calculating int minR1 = infinity, maxL1 = -infinity; int minR2 = infinity, maxL2 = -infinity; for (int i = 0; i < n; i++) { maxL1 = max(maxL1, a[i].first); minR1 = min(minR1, a[i].second); } for (int i = 0; i < m; i++) { maxL2 = max(maxL2, b[i].first); minR2 = min(minR2, b[i].second); }

  • »
    »
    10 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    maxL1, maxL2 — maximum left ranges in chess variants and programming variants

    minR1, minR2 — minimum right ranges in chess variants and programming variants

    Then we use them for both cases. In first case we need the distance between minimum right chess range and maximum left programming range. So we simply use maxL2 - minR1. The same in the second case.

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

In problem 785D Anton and School 2 for the case when we have x opening brackets and then y closing, total number of RSBS according to the editorial

Should we subtract 1 from it? (case when we have x ones in the beginning and then y zeros as I understand is empty sequence which is not RSBS according to the statement).

I was thinking in a bit different way about number of RSBS when we have x opening brackets and then y closing, if we sum over the length of first half we can find that number of RSBS is:

But I don't know how to simplify this one. Maybe someone was doing similar things and achieved result?

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +5 Проголосовать: не нравится

I just solved problem E today. I can see somebody here has same approach with me: using Balanced BST (I choose Treap) on segment tree. My second submission run in O((N + Q) × log2(N)) time complexity and I got TLE. Then I reduce my solution to O(N × log(N) + Q × log2(N)) time complexity and got AC by reducing the build tree step to O(N × log(N)) time. More over, each node is a treap can be built in O(N) time. Hope this help someone implement this problem easier.

»
10 лет назад, скрыть # |
← Rev. 4  
Проголосовать: нравится -8 Проголосовать: не нравится

Isn't it the algorithm for Problem D?

But I am getting Memory limit exceeded on test 6 verdict :(

My Code
  • »
    »
    10 лет назад, скрыть # ^ |
    ← Rev. 3  
    Проголосовать: нравится 0 Проголосовать: не нравится

    But I am getting Memory limit exceeded on test 6 verdict :(

    Consider how much memory the line

    vector<int> dp[200001];
    

    consumes. It'll be bytes, which is about 20 GB. It won't fit any time limit.

    Isn't it the algorithm for Problem D?

    Yes, it is, but you need a way to find the number of combinations faster. To do this, you can look at my code, which is in the editorial.

    To do this, you can use a naive formula . To calculate this fast, you can do the following:

    1. Precalculate all the factorials under 106 by modulo.

    2. Learn how to divide by modulo. Dividing by modulo means multiplying by an inverse element. How to find the inverse element, see the article

    P. S I recommend you not to place you code directly in the comment. You may place a link to submission instead, or place your code to ideone or pastebin and provide a link to it. Or you can use spoilers, like this:

    C++ code
»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Hello, can some tell me what is wrong with this solution with C problem? 25806694

Thanks in adavanced.

»
10 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

why to use the logn time complexity ? This can be done in O(1). We dont need to use the binary search.

At the end of mth day the no of grains in the barn is n — m; from the next day it will be like (m — (m+1) , (m — (m+2)), ... , (m — (m+k)) which can be written as k * (k+1)/2. lets formulate the equation n = (k *(k+1))/2. hence k^2 + k — 2*n = 0; the root is (-1 + (sqrt(1 + 4*2*n))/2. let this be s. if(s*s + s < 2*n) then add a day. day = m + s is the answer.

»
10 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +16 Проголосовать: не нравится

785D — Anton and School — 2

I think this sentence is not correct in solution : number of RSBS in string that begins with x characters "(" and ends with y characters ")" equal to ( x + y)! / ( x! * y! )

it must be : ( ( x + y)! / ( x! * y ! ) ) — 1

Why we subtract 1 ?

In solution written that : formula also means the number of ways to match the string with the sequence of zeros and ones of the same length, which contains exactly x ones

Lets look picture in example : ( ( ( ) ) ) )

one combination is 1 1 1 0 0 0 0 If we create string with following algorithm which is written in solution : all the opening brackets that match zeros and all the closing brackets that match ones Resulting string will be empty string. And empty string is not RSBS. And this means we must subtract 1 . But Code work fine. Because in code we write ( x + y-1)! / ( x! * (y-1)! )_ ( explained in solution ). This prevent taking empty string

»
9 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Can someone help me with my solution of Problem E ? Link: https://ideone.com/500vNF I am using segment tree with each node having a set .

»
8 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

In the solution of problem C,why is the upper limit of binary search 2e9??