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

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

990A - Комментаторские кабинки

Разбор
Решение (PikMike)

990B - Микромир

Разбор
Решение (adedalic)

990C - Конкатенация скобочных последовательностей

Разбор
Решение (Ajosteen)

990D - Граф и его дополнение

Разбор
Решение (Ajosteen)

990E - Уличные фонари

Разбор
Решение (PikMike)

990F - Управление потоками

Разбор
Решение (PikMike)

990G - Подсчёт GCD

Разбор
Решение с Мёбиусом (Bleddest)
Решение с центроидом (adedalic)
  • Проголосовать: нравится
  • +59
  • Проголосовать: не нравится

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

990E — Уличные фонари

Unable to parse markup [type=CF_MATHJAX]

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

Халявин , типичный халявин . У многих задачи упали )0))). Спасибо за интересный контест и разбор.

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

Интересно, только я в разборе задачи E ни черта не понимаю?

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

"Изначально считаем только 0 покрытым." В смысле, в нуле лампа? Но мы же начинаем справа?

"Функция f(i) — минимальное количество ламп, требуемых для покрытия отрезка [0;i] очевидно монотонная, поэтому обновлять состояния мы хотим как можно раньше." Замечательно, что эта функция упоминается в первый и последний раз. Что за состояния мы хотим обновлять, тоже непонятно.

"Ага, теперь почему это быстро? Разумеется, предпосчитаем самую правую свободную позицию для каждого префикс-сегмента." И тут внезапно появился загадочный "префикс-сегмент". Это вообще что такое?

"Наконец, любые две последовательные итерации алгоритма либо подвинут на k+1 позицию, либо вернут -1. Это можно легко доказать с помощью противоречия." Подвинут что?

  • »
    »
    6 лет назад, # ^ |
      Проголосовать: нравится +1 Проголосовать: не нравится
    1. Покрытие отрезка [0, n] строится жадно: поддерживаем длину префикса, освещенного лампами, и на каждом шаге для следующей лампы выбираем самую правую свободную клетку из данного освещенного префикса.
    2. Первоначально длина префикса равна 0, то есть можно считать, что покрыта только точка 0.
    3. Функция f(i) введена только для доказательства верности жадного алгоритма и в самом алгоритме не используется.
    4. Префикс-сегмент  →  префикс: предподсчитаем для каждого префикса самую правую свободную клетку (описано в 1).
    5. Подвинут правую границу покрытого префикса из 1.
»
6 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can someone explain a bit more about the complexity for the problem E "Post Lamps" ?

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

    Essentially it uses the fact that the sum of reciprocials of numbers up to n is about ln(n) for large n. The proof outline is as follows. We start from the fact (1+1/n)^n<e<(1+1/n)^(n+1). Now by taking logarithm we get that 1/(1+n)<ln(1+1/n)<1/n. Summing over all n gives desired.

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

I passed GCD Counting with . Was a solution with that complexity intended to pass?

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

    Was your solution for each subtree, calculate number of paths into the current node with each gcd and then find the contribution of each pair of paths from different subtrees? I wrote such a solution but I believe the complexity can be bounded by 160 N log N. This is for the case of a k-ary tree where we have f(N) = k f(N/k) + 160 N. Other trees only seem to require less operations — a line graph is only 160N.

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

In Problem G , solution with centroid's code , there's an extra " ' " in the countdown fifth line of function "solve()" .

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

      Thx . I seldom use C++14

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

      But I think you should consider removing it from the model solution as it looks like it's not being displayed correctly on codeforces. The entire code after the seperator is having a green color which is very confusing for someone trying to read the solution. Seems like cf cannot display this feature correctly for code in markdown.

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

in problem E the answer of first example ,if I let the lamp has 1 power place in position 0 2 4 5 then segment【0;n】 can be covered ,the answer is 4 why?

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

awoo Can you explain the complexity of your " get " function for the problem E Post Lamps ?

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

    get(i) takes about steps to finish. Then it's the same as in Eratosthenes sieve, for example. in total.

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

      I think it takes more than n / i steps for every i since we are not iterating on the multiples of i. But I am not able to bound it to n / i . Can you give an explanation for the bounding part ?

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

        It takes more than but it is . Try doing two steps. You put segment, find the next free position, put another segment. Either the next free position will be i + 1 away from the first one, or you will quit function immediately. Then you reach n in about steps with some constant factor.

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

          May be, We can block some positions such that every i (1 to k) will take O(n) steps. Won't that make this algorithm O(n*k) which will TLE. Or can we always prove that complexity is O(n*lg(n)) ?

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

            OMG, guys, can't you like draw it yourselves?

            Imagine the worst case for placing two segments. It's when there are just two free positions and then lots of blocked ones. So you put one to the first position, one to the second position and then you will go right to l + 1 from the first free position or there will be no free spaces.

            y = 0 is the axis (black is blocked, white is free). The other two are two placed segments.

            You can draw other cases with less blocked positions, with more free positions to the left and see that the case I drew is the worst of them.

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

In G; anyone care to explain how this relation is derived?

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

    We can use inclusion-exclusion to get the following:

    , where S is some set of prime numbers (possibly an empty set), and p(S) is the product of its elements (and h(p(S)) denotes the number of paths where gcd is divisible by every prime from S).

    The number of such sets is infinite, but since for every p(S) > 2·105 h(p(S)) = 0, we can iterate on the numbers from 1 to 2·105 and check whether there exists some set such that p(S) is equal to this number.

    In fact, if some number x is divisible by some number q2 (where q is prime), then there is no set S such that p(S) = x (and μ(x) = 0). Otherwise, there is exaclty one set which is the factorization of x, and μ(x) =  - 1 if and only if the size of this set is an odd number.

    Is this explanation clear? Or should I clarify something?

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

    For a way that relies more on the mobius inversion, it's easy to see that

    To see this, take h(5). The number of paths whose gcd is divisible by 5 are all the paths who have a gcd of 5, 10, 15, 20, etc. Now, there's an alternate form of the mobius inversion that states that

    Thus, to get a formula for ans, it's simply

    As an explanation for this alternate form, take a look at https://math.stackexchange.com/questions/1965342/does-the-mobius-inversion-theorem-hold-when-sum-function-is-over-multiples-inste

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

    At line 41 Use :
    int cntop[maxn]={0}, cntcl[op] ={0};
    Instead :
    int cntop[maxn], cntcl[op] ;
    rep(i,maxn) cntop[i] = cntcl[i] = 0 ;

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

Can someone explain the solution with centroid decompression in the problem G?

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

    Key idea of this solution is next: let's look at the subtree in decomposition with its centroid c. You need to calculate all paths which go throw c, so its gcd will be divisors of a[c] and there will be no more than K different divisors of a[c] (K ≤ 160). So if you process each subtree (subtrees are formed by childs of c) not with but with (checking each gcd still takes O(K) operations) complexity will reduce from to something like .

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

      Apparently a centroid decomposition involves recursively finding the centroid of each subtree, so this is not actually a centroid decomposition since the centroid is found only once. I believe this is only a constant-factor speedup over the naive O(NK log N) solution I described here, which was fast enough, runs in about 1 second.

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

        I could miss something, but my proof was next: Let's look at all subtrees, which appeared in decomposition.

        Proposition: there O(N / K) subtrees with size at least K (let's name them big). To prove it, let's find all big subtrees which don't contain any other big subtree. There is no more than N / K such subtree. Let it will be 0-level. Let's look at subtrees, which contains 0-level subtrees. Name them 1-level. Since it's centroid decomposition size of each subtree of 1-level at least twice of size of 0-level. So there are no more than N / 2K such subtrees. And so on. So there no more than N / K + N / 2K + N / 4K... = O(N / K). Each big subtree is processes with O(K2) time. So total complexity for big subtrees is O(N / K·K2) = O(NK).

        Similarly, There are O(N) small subtrees, but each small subtree of size x is processed with O(xK) time. But there are no more than levels of small subtrees since after that they become big and each level is processed with O(NK) in total. Here we came to final complexity. Of course there is also to build decomposition and or to calculate gcd-s.

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

          Ah, I think I misunderstood your last comment. It seems you are using a legit centroid decomposition, so the complexity makes sense. At first I didn't understand how centroids would work, since you calculate paths to the middle, but then for the parent calculation you need a different set of paths. But I guess you could find most of those by taking the gcd of the path to the centroid and the path from the centroid to its parent.

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

I think that tests for problem E are weak, because my (I think!) wrong solution passed. I'll try to explain my logic:

Firstly, note that F(i) (editorial explanation) is decreasing with an increase i.

Second, assign every a[i] to min(a[j]), i <= j (obviously???)

a[i] is increasing with an increase i.

So we have two functions F(i) and a[i], answer for fixed i is F(i) * a[i].

Now every a[i] change to  - a[i].

So we have two decreasing functions.

Now launch ternary search xD

Answer is maximum F(i) * a[i] multiplied by -1 (because we changed a[i] to  - a[i]).

Please hack me, because no one was trying to do it (maybe, I'm a lucky one)

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

    I found a hack to your solution.

    720720 0 100
    100 199 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 100000 100000 100000 100000 100000 100000 100000...
    

    Your program outputs 720720000 while the correct answer should be 199*(720720/2)=71711640

    I chose 720720 because it is the LCM of 1..16 so the first numbers all divide evenly into N. Then, you make the first few numbers cost equal to its size, so they all cost the same, so ternary search can't find the one that costs slightly below it's size. I padded on the 100000s so that it won't run into your brute force when the range is too small.

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

Can anyone explain E? I struggling going through it. And why he has chosen this approach and its proof? Help!

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

    It goes like this. You come up with straightforward O(n3) dp solution. Then you check the constraints and decide that there should be a greedy solution, not a dp one. After that you check which states are actually useful when updating the next states. Finally, you code it greedy using some precalc values to achieve the right complexity.

    The proof can be found in earlier comments of this blog.

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

can anyone please explain problem C? I am not able to get the intuition to it from the editorial. Thanks in advance !

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

Concerns about Problem: E Post Lamps.

Why are all the lamps being considered? Should not only ONE lamp with power >= 'some value L' and having the least cost be the optimal choice?

e.g: Suppose the maximum length of consecutive forbidden positions is 'L'. Then we must use a lamp with a power of at least 'L+1'. (We may put this lamp just before the start of that forbidden segment).

Now isn't it better to use a lamp with a power greater than 'L+1', but having a smaller cost? But this is not giving the optimal answer for some reason. I can not seem to find any example where a greater powered less cost lamp is not giving better answer.

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

    Let array of costs be increasing array . For each L there are no ''a greater powered less cost lamp'', but optimal answer can be any of L.

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

      Thank you for your response.

      I am getting it now.

      Here is the case that I was missing:

      pattern: 0XXXXX000

      lamp1: power: 6 , cost: 10 , ans: 2*10 = 20 ( 2 piece needed )

      lamp2: power: 8 , cost: 11 , ans: 1*11 = 11 ( 1 piece needed )

      Optimal answer is obtained by lamp2.

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

I finally managed to pass tests with my solution for G. It is stupid dp on trees technique dp[v] = sack with pairs <gcd number, amount of paths>. Dp counted bottom-up then top-down. I think it can be hacked by ML verdict with careful test. Submission

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

For F, visualize the graph as follows. Add two extra nodes, a source node from which water comes and a sink node to which water flows. For the remaining nodes if a node has a positive value of Si then water is flowing out of the node to the sink node and if it has a negative value of Si water is flowing into the node from the source node. All that we need to do now is to balance the flow. In order to do this, find a spanning tree of the graph and then for each node, calculate how much water should flow into/out of it's subtree, add the input/output of the current node and pass the remaining water to it's parent. Reference code: http://codeforces.com/contest/990/submission/40238544