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

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

Задача A.

Все что нужно было сделать в этой задаче — разобрать несколько случаев. В силу того, что все числа были до 108 вычисления проводить можно было в 32-битном типе данных.

Разобрать нужно было следующие случаи:

  • Дом первый магазин второй магазин дом

  • Дом первый магазин второй магазин первый магазин дом

  • Дом второй магазин дом первый магазин дом

  • Дом второй магазин первый магазин второй магазин дом

Асимптотика: O(1)

Задача B.

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

Затем нужно пройти по массиву и разобрать несколько случаев, предварительно нужно завести флажок для ответа Ambiguity:

Пусть текущий элемент массива — bi

  • Если существует более одного элемента, из которого можно получить bi, то нужно поднять флажок, который отвечает за Ambiguity
  • Если не существует ни одного элемента, из которого можно получить bi, то нужно вывести Impossible
  • Если элемент один, то просто заменяем bi на число, из которого мы могли получить данное bi

В конце, если флажок поднят, то нужно вывести Ambiguity, иначе Possible и полученный ответ.

Асимптотика: O(N)

Задача C.

Первым делом нужно понять, как выглядит оптимальный ответ.

Пусть Hi — отсортированная последовательность hi. Пусть E — множество индексов последних элементов каждого блока. Тогда утверждается, что e E, отсортировав первые e элементов последовательности hi получатся в точности e первых элементов последовательности Hj.

Тогда, нетрудно заметить, что размер E будет являться ответом на задачу.

Для начала нужно посчитать два массива: prefmax и suffmin, где prefmaxi — максимум из элементов a1, a2, ..., ai, а suffmini — минимум из элементов ai, ai + 1, ..., an.

Чтобы получить ответ, нужно посчитать количество индексов i таких, что prefmaxi  ≤  suffmini + 1.

Асимптотика: O(N)

Задача D.

Будем решать задачу для n ≤ m, затем просто поменяем местами и выведем ответ. Нужно не учесть квадраты два раза!

Давайте воспользуемся следующей формулой для фиксированных n и m (n ≤ m) и чтобы вычислить x.

Если еще немного упростить, то получим

Затем применяем сумму квадратов и сумму первых k чисел для решения этой задачи.

Получаем 6x = 6n2 * m - 3(n2 + n3 - nm - n2) + 2n3 - 3n3 + n = 3 * m * n2 + 3 * m * n - n3 + n

Так как мы решали для n ≤ m то 3n2 * m =  ≈ n3, а это значит, что n можно просто перебрать до двух корней кубических.

Асимптотика:

Задача E.

Решение этой задачи — динамическое программирование.

Пусть froot, mask обозначает количество способов построить дерево с корнем в вершине root на множестве вершин mask с соблюдением всех условий. Для удобства, будем нумеровать вершины с нуля.

Тогда, понятно, что ответ — это ни что иное, как f0, 2n - 1.

Тривиальными будут состояния, где в маске только лишь один единичный бит. В таких случаях froot, mask = 1.

Будем считать эту дп рекурсивно с запоминанием состояний. Чтобы сделать переходы, нам нужно выбрать какую-то маску newMask, которая обязательно является подмаской маски mask. Затем следует перебрать корень newRoot в маске newMask. Так же, для того, чтобы не посчитать одно и то же дерево несколько раз наложим условие на маску newMask. А именно, будем брать только такие маски newMask, в которых старший бит (не отвечающим за root) совпадает со страшим битом (не отвечающий за root) маски mask. После чего, нужно проверить выполнение всех условий на ребра и на lca. Если все хорошо, то обновить . Где — исключающее или.

Что касается проверки, на lca то ее можно делать за O(N2) — предварительно для каждой пары запомнив lca или в худшем случае за O(Q) просто пробегая по всем парам вершин, для которых какая-то вершина v является lca. В случае с O(Q) состояний достижимых не очень много и поэтому дпшка будет работать довольно быстро.

Асимптотика: O(3N·N3) или O(3N·N·Q)

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

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

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

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

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

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

Thanks for nice editorial and Nice contest!

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

Thanks for nice editorial and nice contest :)

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

Problem A: this line min(d1, d2) + min(d3, d1+d2) + min(d3+min(d1, d2), max(d1,d2)) solves it.

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

In the problem D don't we search n in the range [1 X^1/3] and then for each n, m in the range [n,x^1/3]? Is overall complexity O(x^1/3) or O(x^2/3)?

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

Problem C:

I solved it in nlog(n):

I will illustrate on this example:

4 3 4 1 2

  • first, I sort the array keeping the index of each element with it as a pair. the resulting array will be like this:

(1,3) (2,4) (3,1) (4,2)

and then iterating through this array and know each element should go from where to where (so this segment must be sorted as one partition). For example:

element with value 1 must go from index 3 to 1, so segment(1,3) must be updated.

for Every such segment I either: 1- insert it into a set. 2- if it intercepts with other existing segment in my set, I update both of them into a new segment.

for example: first I insert segment (1,3), then it comes (2, 4). I merge both into one segment which it is (1,4).

lastly, I get the number of segments seg and the total elements they have in them tot, and answer is seg+n-tot

my code: 14383376

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

Fastest system testing ever! And super fast editorial. Great job. Ciao.

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

це була изи катка

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

Выдели задачи, а то сливаются

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

Problem D — Spongebob and Squares is a beautiful problem, kudos to the author

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

I think there is much nicer/easier solution for problem C. I think it work?

Say you have the array elements a1, a2, ..., an. Then, call them sorted be b1 ≤ b2 ≤ ... ≤ bn. Then, for each 1 ≤ i ≤ n, we check if a1 + ... + ai = b1 + ... + bi, and if so, we increment ct++. (If sum are equal, then element must be equal because it is the minimum possible sum). Then ct will be the answer.

Implementation: 14386133

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

    Can you please tell me why the statement " If sum are equal, then elements must be equal" is always true ? Although I noticed this fact with few examples, but I couldn't prove it.

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

sorry, in problem C when you say H_j is H_i right?

  • »
    »
    8 лет назад, # ^ |
    Rev. 4   Проголосовать: нравится 0 Проголосовать: не нравится

    This isn't the only point that confuses me :) I'd actually appreciate if someone wrote a simpler and more detailed explanation for the problem C (at least, by filling in the gap in the logical steps before the sentence 'Firstly, we need to calculate two arrays').

    It would also be really great to start seeing the tutorials with pictures. For some reason the pictures are used to describe the problem statements, but they are avoided when they try to explain the solution for those who didn't solve the problem ;)

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

For problem D: won't the equation be: 6x = 3mn2 + 3mn — n3 + n. I solved using this equation and got accepted. Here is the solution : 14387650

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

    I use the same equation as yours, and I'm confused by the equation in the editorial. Anyone who can explain that? Thanks. :)

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

    but how it is possible??

    can you please explain.....

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

      I had got the similar general equation as :

      but when I proceed to solve it I got:

      6x = 6mn2 — 3(n+m)*(n)*(n-1) + (n)*(n-1)*(2n-1)

      I got the above equation after expanding the summations that is sum of k intgers and sum of k squares, here k = n-1.
      On further simplification we get the equation I mentioned above :

      6x = 3mn2 + 3mn — n3 + n.

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

My solution for D does not work for certain numbers, but still got AC. (Only sad thing is that I submitted the 'right' solution with an upperbound of instead of , which got hacked. Didn't know that would discard my accepted solution too.)

Let n < m. We can derive that 6x = n(n + 1)(3m + 1 - n). (By the way, you forgot the  - n3 in the final formula in the editorial.) What I did: first factorize 6x. Then, generate all divisors of 6x. Now, sort the divisors, and check for each divisor d whether d + 1 is a divisor too. (Thus, whether it equals the next divisor in the list.) If both d and d + 1 are divisors, set n = d and solve for m. If m is an integer, we have found a solution.

The problem is that we can only factor numbers with at most one prime above 106. (Or 107, but that doesn't really help.) The algorithm fails when 6x has two consecutive divisors and two large factors. In particular, this might happen when 6x = 2·3·p·q, and p = q ± 1, p = 2q ± 1, p = 3q ± 1, p = 6q ± 1 or 2p = 3q ± 1. (Although the first case can't happen.) I was to lazy to check each of theses cases separately, but it still passed when I resubmitted it after the contest. I think this solution should have been proven wrong by the system tests, but one can always miss some weird solutions. It was a nice contest anyway!

Solution

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

    I got AC with the same equation without handling any special case...

    6x = n(n + 1)(3m + 1 - n)

    since n and (n+1) can not have any common factor and 6x/(n*(n+1)) should be integer,

    it means 6x should be divisible by n & (n+1) individually...

    and as we assume m>=n

    it means (3m+1-n)>=2*n+1

    hence 6x/(n*(n+1))>=(2*n+1)

    so just run a loop for all n with above conditions

    code: 14383578

    time comp.-> O(cuberoot(x))

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

      Yes, you're right. Since , we only have to know the divisors (or factors) of x up to 2·106. This excludes all my special cases. I clearly wasn't thinking straight yesterday.

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

in problem B : why don't when i find count of some element b[i] more than 1 immediately print "Ambiguity", is it wrong ?

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

    3 3

    1 1 2

    1 1 3

    If you print "Ambiguity" then there should exist several sequences that satisfy the sequences F and B, but in this case, even though there is ambiguity with the 1's, it's impossible because a 3 never appeared in the sequence F.

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

How is my logic wrong for A, I only got till pretest 4,I put these 4 values into integers

  1. d1+d2+d3
  2. 2(d1 + d3)
  3. 2(d2 + d3)
  4. 2(d1 + d2)

and then I put these integers into an array and I wrote a for loop to find the minimum value

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

    Hi, I have read some of your submissions. Your logic is right, but your code have some implementation bugs. For example, you store the minimum in an unitialized int variable named 'o'. The default constructor initializes 'o' with some undefined value. That's why your code outputs a 0 in the first case ('o' is initialized with zero). In your last submission, if all the distances are equal, you are not printing anything. You are looking for a number in that array that is strictly less than all the others. Finally, make sure that you are inserting exactly the values (d1+d2+d3), 2*(d1+d3), 2*(d2+d3) and 2*(d1+d2) (I think you are inserting 2*(d1+d2)+d3 instead of d1+d2+d3).

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

Problem D. 6x = -n^3 + 3mn^2 + (3m+1)*n

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

What's wrong with my submission? I cant figure it out.. http://codeforces.com/contest/599/my#

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

In Problem B , I did the same thing as mentioned here but its failing in the system tests , Test case #10. Its a pretty large test case so i am able to figure out the bug.

Can anybody tell me whats wrong ? Here's the link to code : http://codeforces.com/contest/599/submission/14373418

Would be great if anybody could help. Thank You.

»
8 лет назад, # |
Rev. 5   Проголосовать: нравится +6 Проголосовать: не нравится

For problem D, I assumed that m = (6x + n3 - n) / (3n2 + 3n) is decreasing because data seemed like it. So n's upper bound is when . When 6x gets bigger n gets bigger. So n's upper bound is when 2n3 + 3n2 - n = 6 * 1018 therefore n ≤ 1442249. Fortunately, this got accepted. But after the exam I looked at some m - n graphs for various x values and realized that this is not monotonically decreasing, instead it first goes down, and after n = m it goes up again. I'm wondering if there's any integer (n, m) pairs where n is bigger than the first intersection point (a.k.a my pseudo upper bound). If not, how to prove it?

Graph of the first test case of the problem:

UPD: Nevermind me :D I don't know how I couldn't see n is always bigger than m after intersection (even though m starts to increase again, it increases more slowly compared to n) by looking at that graph.

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

The problem D.X<=10^18?WA65....

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

Не понял решение задачи E... За счёт чего работает такой пересчёт динамики, когда мы берём только маски, у которых совпадают старшие некорневые биты? (кажется немного магией :) )

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

Как получилась формула 6x = 3n2 · m  +  3n·m  +  n ?

У меня получилось: 6x = 3n2·m - n3 + 3n·m + n (AC: 14396538)

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

problem B is failing on test 20 and i can't figure out the bug. can anyone help me ?

here's my code 14400028

  • »
    »
    8 лет назад, # ^ |
    Rev. 2   Проголосовать: нравится +1 Проголосовать: не нравится

    You can have situation when you say: "Ambiguity" and return 0, but after your answer you have f[i] that not exist... For example: n = 4, m = 2, f = {1, 1, 3, 4} b = {1, 50} Answer: Impossible

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

    you should test that the solution "possible" before saying "Ambiguity" because you say that there is many solution but actually there is no solution

    • »
      »
      »
      8 лет назад, # ^ |
      Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

      correct me if i'm wrong

      i'm checking like this

      1- if the number doesn't exists in (F) print impossible close the program, else continue

      2-if the number exists more than once in (F) print ambiguity close program ,else continue

      3- if the number passes all the above then it's possible to find a solution ,store number in an array

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

        2nd point is wrong.

        If you say there is ambiguity, then there should be several ways to create a sequence A that satisfies the sequences F and B.

        Check this case

        3 3

        1 1 2

        1 1 3

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

        In your 2nd point, you can't close the program if you get ambiguity, as it is possible you get "Impossible" later. An impossible solution also may have ambiguities.

        So keep a flag for ambiguity. If you find solution is not "impossible", then and only then print ambiguity, and else the answer.

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

About problem C:

I got wrong answer in test case 7 which is:

25

1 2 3 4 4 4 4 4 4 4 2 3 5 5 7 9 8 5 10 12 15 12 100500 800600 228228228

My output: 13 Jury's output: 12

The maximum number of blocks was asked to find out. In this test case my partition is: [1][2][3 4 4 4 4 4 4 4 2][3][5][5][7 9 8 5][10][12][15 12][100500][800600][228228228] -->> total 13 blocks.

Could anyone tell me where I am doing mistake?????

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

    In your answer [1][2][3 4 4 4 4 4 4 4 2][3][5][5][7 9 8 5][10][12][15 12][100500][800600][228228228]

    The 3rd and 4th block have to be merged as 3 is less than 4. So finally you will have 12 blocks, which is the answer.

    [1][2][3 4 4 4 4 4 4 4 2 3][5][5][7 9 8 5][10][12][15 12][100500][800600][228228228]

    I was making the same mistake you were. Let us see what that mistake is with an example.

    4 3 6 1 2 5

    I was finding for every element, the last index among all elements which are less than it. So for 4, I find that 2 is last element less than it, so I formed the blocks

    [4 3 6 1 2][5]. But this is incorrect.

    What I didn't consider is that in the newly formed block there maybe some element greater than the start of the block,, and that will introduce more inversions. So here, 6 is greater than 4, so 5 also has to be included in the block. Hence final block is [4 3 6 1 2 5]

    Hope you get the point.

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

in PROBLEM B

I adjusted my code and it's failing on test 28 .the weird thing is that test 28 gives me the correct answer when i run it on my PC but gives a completely different answer on the judge's system. here's the submission 14411133

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

    In your code, you need to set your "bool exists[]" array to zero. Since you are not doing that, your bool array is getting garbage values and hence your answer is wrong.

    So, either declare the array as global(which automatically sets it to zero), or do a memset, or go through the array in a loop and set all values to zero.

    Here is the AC submission: AC

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

D Getting 6x = 6n2 * m - 3(n2 + n3 - nm - n2) + 2n3 - 3n3 + n = 3 * m * n2 + 3 * m * n - n3 + n wrong? Is this? Getting 6x = 6n2 * m - 3(mn2 + n3 - nm - n2) + 2n3 - 3n3 + n = 3 * m * n2 + 3 * m * n - n3 + n

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

Can someone explain E in more detail ??

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

Can someone please give the necessary resource links(blogs,tuts etc) for understanding problem E as could not understand it

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

Hey, I was upsolving some problems and one of them was E of this contest.

I liked the problem and after reading the editorial and some silly mistakes in the implementation I got accepted and feel that I learned something, but there's something I don't understand in the editorial, the time complexity.

I understand how to check the fulfillment of the conditions before a transition in O(N3) or O(N·Q) but I don't understand where does the O(3N) come from.

Could anyone give me an explanation or at least some hints about the 3N? ;)

Thanks :)

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

    Although I'm a beginner , luckily I know why 3^N.( my English is poor, sorry ) All of the states is 2^N, that is no problem. For every state that has i of 1 in its bits( 11101 is 4, 11001 is 3, 10011 is 3) the number of submasks of it is 2^i(other bit is 0) so the equation is C(i,N)*2^i ( 0 < i <= N ) so it's 3^N This thing has also been used in the solution to Steiner Tree, maybe you can google it. Hope helpful to you.

»
23 месяца назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

tfw you solve problem C with sieve of eratosthenes

»
3 месяца назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can Anyone help me in understanding the testcases of problem B.