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

Автор awoo, история, 14 месяцев назад, По-русски

1796A - Typical Interview Problem

Идея: BledDest

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

1796B - Asterisk-Minor Template

Идея: BledDest

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

1796C - Maximum Set

Идея: BledDest

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

1796D - Maximum Subarray

Идея: BledDest

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

1796E - Colored Subgraphs

Идея: BledDest

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

1796F - Strange Triples

Идея: Neon и adedalic

Разбор
Решение (Neon)
  • Проголосовать: нравится
  • +93
  • Проголосовать: не нравится

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

high quality problemset

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

В Д (мне кажется) более понятная и лёгкая ДП — dp[i][k] — максимальная сумма подотрезка, заканчивающегося в i, если уже увеличили на x в k позициях.

Пересчёт понятный, в k приходим из (k — 1 или k) или отрезок длины 1. обновляем ответ по каждому значению на каждом слое, так как отрезок ответа должен где-то закончится, в этот момент и поймаем его. Главное не забыть, что не все конфигурации i k допустимы и проверять, что не использовал +x на больше позиций, чем прошёл. Или что не осталось использовать на большем количестве, чем осталось элементов.

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

    I have implemented this idea, but because it didn't work, I decided that idea is wrong (there is a flaw in it).

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

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

    У вас есть отдельная проверка на $$$K = 0$$$ (даже если допустить, что у вас не будет отдельной копипасты всего вычисления динамики).

    Появляются дополнительные сценарии перехода с условиями, которые легко потерять или перепутать (суждение субъективное, я так вижу описанные вами внутренние переходы динамики)

    Ответ надо искать по всем состояниям динамики, не забыв проверить определенные базовые состояния.

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

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

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

      Я примерно поэтому и добавил (мне кажется). И мне действительно кажется, что динамика "сумма заканчивается ровно здесь" сильно легче интуитивно понимается, чем что-то с 3 флагами и "не зашли, вышли, внутри". Хотя этот метод что-то там ещё прикольное решает конечно.

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

Can someone check why is it giving TLE on Test Case 3 in C? I used binary search.. https://codeforces.com/contest/1796/submission/195465321

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

    I haven't checked the details of your code, but one common issue with C is that participants don't realize that there is no bound on the total size of $$$r$$$ over all test-cases. So you can theoretically have $$$20000$$$ test-cases that all have $$$r$$$ at or near $$$10^6$$$. With this knowledge, you may able to figure out why your approach TLEs. You're basically restricted to logarithmic time or better, i.e., $$$O(\log r)$$$ time (maybe a highly optimized sublinear polynomial might pass, but idk)

    But if you were conscious of this when estimating your time complexity, then the issue is likely something else...

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

    What kind of BS you used. Looks like just iterate over [L, R].

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

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

Can someone tell me what i did wrong with problem B? Im always getting error on test 2 but i cant figure out what is wrong with my code

https://codeforces.com/contest/1796/submission/195477231

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

    you should add a condition if(flag2==false) for outer loop you just added it for inner and if statement only that's why check for this output it will give multiple yes aabaaba babbabb

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

For problem D, can someone help me see why my top down solution TLEs but the bottom up solution passes? Top down: 195483749 Bottom up: 195485579

  • »
    »
    14 месяцев назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится
    Spoiler
»
14 месяцев назад, # |
  Проголосовать: нравится +21 Проголосовать: не нравится

For Problem E

After rooting the tree at vertex 1, I greedily rooted the tree at the leaf of the shortest vertical path. Two iterations were enough to pass the test cases. Maybe someone can give me a counter test? I am not sure of the correctness of this greedy solution. Submission link.

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

    Huh, this might be correct. I did some stress testing and couldn't find a counter test. Can't quite come up with a proof, though.

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

You: You

The guy she tells you not to worry about: The guy she tells you not to worry about

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

Can anyone please help me understand why my code gives TLE?

https://codeforces.com/contest/1796/submission/195509093

I basically followed the editorial exactly but used memorization instead of bottom-up.

In general, is bottom-up faster, or is my implementation just flawed?

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

    Did you find the answer?

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

      I needed to change the line "else if (cache[i][j][t] != 0)" to "else if (cache[i][j][k] != -1)" and default all values in the array to -1. That way you can precompute the answer to states where the answer is 0, which is much faster.

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

For D i didn't read that $$$k \le 20$$$ so I ended up with a solution that I think is $$$O(n \log n)$$$ (independent of k) rather than $$$O(k n)$$$

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

I was so close with C but didnt realise that these powerful restrictions on di take place, very cool

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

problem D can be solved with k<=10^5 in O(nlogn).

check my submission: https://codeforces.com/contest/1796/submission/195344685

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

For problem C can someone help me why I got wrong answer ? I thought I was very close to the answer,Submission here:195398117

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

on question C why there is no mod in solution code but it still gets accepted?

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

    I found it too. I had considered the correct solution, but it didn't require any mod, so I missed the chance to get an AC.

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

    the numbers never go over 998244353

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

[deleted]

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

What is the greedy method for D task?

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

For problem E, I don't think it is necessary to save all the length, just the top three, which is O (n)

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

    Yeah, I mentioned that in the tutorial. You can do that but it is more annoying to code and is not that much faster under the given constraints.

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

why my solution is giving TLE on test on problem D my submission link :195537978 i used multiset for implementation and used greedy logic.

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

居然没中文

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

In problem C:

For some reason my code written in C doesn't work but same code submitted as C++ code got accepted

C Code: https://codeforces.com/contest/1796/submission/195570786

C++ Code: https://codeforces.com/contest/1796/submission/195570367

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

    Found out the reason, integer overflow.

    GNU C11 doesn't have 64 bit ints and GNU C++20 (64) has.

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

      What do you mean by "GNU C11 doesn't have 64 bit ints"?

      I don't know why your code doesn't work in C (the only obvious difference I see is the d=1<<k; vs d=(1L)<<k; line), but C11 does have long long int which is 64 bit.

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

        I should clarify GNU C11 does have 64 bits ints but codeforces one's is only 32 bit same with GNU C++ 14 and GNU C++ 17 and long long int are 32 bit ints with these 3 compilers and d=(1L)<<k or d=(1LL)<<k doesn't seem to work as well

        1LL in GNU C11 code https://codeforces.com/contest/1796/submission/195732043

        1L in GNU C11 code https://codeforces.com/contest/1796/submission/195570188

        1LL in GNU C++17 code https://codeforces.com/contest/1796/submission/195732012

        All these codes would work in GNU C++20 (64) so the problem can only be due to 1 of 2 reasons:

        1. scanf() or printf() not handling long long ints properly

        2. complier not supporting 64 bit int and integer overflowing

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

          Yeah, it's the first reason. See 195959191 and 195959158.

          The problem is in the line printf("%lld %lld\n", 1, right+1-left);. 1 here is a 32-bit int, but it gets passed as 64-bit. I think you even end up reading from unallocated memory (or memory allocated for something else). The fix is either:

          printf("%lld %lld\n", 1LL, right+1-left); or

          printf("%d %lld\n", 1, right+1-left);

          I can reproduce the erroneous output on my MinGW gcc compiler. Although Code::Blocks outputs the intended output for me (differing from the separately installed MinGW instance, even with the correct/same flags set up).

          Neither compiler report a warning for this, but I have found an online compiler that does: https://www.onlinegdb.com/online_c++_compiler You can see it by pasting in your code.

          long long int is at least 64-bit on all mentioned compilers, as per the standard.

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

Binary search solution for E.

https://codeforces.com/contest/1796/submission/195570895

Actually it is not a good idea to use binary search because checking an answer is more difficult than solving it directly with greedy.

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

For D

I think my solution is O(N) 195675418

Consider the subarray we finally chosed i~j

(let S[i] be the sum of a[1~i])

we can assum x>0 (otherwise we can let k=n-k,x=-x)

$$$j-i>=k$$$: answer is $$$max$$$ { $$$S[j]-S[i]+ k*x -(j-i-k)*x$$$} = $$$max$$$ { $$$ (S[j]-j*x) - (S[i]-i*x)$$$} + $$$2*k*x$$$ }

$$$j-i<k$$$: answer is $$$max$$$ { $$$S[j]-S[i]+ (j-i)*x$$$} = $$$max$$$ {$$$(S[j]+j*x) - (S[i]+i*x)$$$}

both can be easily done in O(N) with a queue

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

In problem B, I need help with the failed test case. 195438093

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

can anyone help me understand the solution of problem f?, the "unique solution to the previous module equation" part

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

    It means once you chose d and r, the value of b' is fixed since it is a value between 10^(|b| — 1) and 10^|b|

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

    More accurate: if $$$b' \equiv - d \cdot r \pmod{10^{|b|}}$$$ then all solutions of $$$b'$$$ can be represented as $$$b' = c \cdot 10^{|b|} - d \cdot r$$$ for any integer $$$c$$$. But since $$$1 \le b' < 10^{|b|}$$$ there is only one solution in these bounds: it's when $$$b' = 10^{|b|} - (d \cdot r) \bmod{10^{|b|}}$$$.

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

Is there a typo in F's solution? "all divisors k1 of (10|n|−1) for a fixed |n|." should it means "all divisors k2" instead?

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

Why does the following greedy solution fail for E: If the tree is a chain then answer is its length. Else, for each degree 1 node find the distance of the closest degree >= 3 node from it and insert {dist, node} into a set. Now pick r to be one of node from the smallest two values of {dist, node}. Thus we erase the smallest two values and insert distance of node1 and node2 into the set as that path is now of same color and the smallest element currently in the set is the ans. Submission link : https://codeforces.com/contest/1796/submission/195404472

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

Greedy Approach for D in $$$O(nlogn)$$$ independent of $$$k$$$:

Prerequisite: knowing how to solve dynamic subarray sum with $$$O(logn)$$$ updates to the array.Submission link and link to solution

Lets split into two cases, $$$x\ge 0$$$ and $$$x<0$$$

First case: Let's assume a subarray $$$[l,r]$$$ is optimal, the sum of this subarray is always sum of $$$a_l, a_{l+1},...,a_{r-1},a_r$$$ $$$+ min(k, r-l+1) * 2x - (r-l+1)x$$$. This is because assuming no positions are selected in the subarray, we just get the subarray sum with $$$x$$$ subtracted from all indexes, however than we assign the most amount of positions as possible for the subarray, when we do this we have to add $$$2x$$$ to every position selected because we already subtracted $$$x$$$ from all positions. This means the positions of the selected indexes do not matter as long as they are in the subarray. It is always optimal for all $$$k$$$ values to be next to each other because compressing the values always makes sure they are in this subarray assuming that the first index is in the subarray, while not compressing the values can leave out values in the subarray. Since we assume that the first index is in the subarray, we can just brute force all $$$n$$$ first indexes in $$$O(nlogn)$$$ time with the dynamic subarray sum mentioned above.

Second Case: The second case turns into the first case pretty easily. We can just represent $$$k$$$ as $$$n-k$$$ and $$$x$$$ as $$$-x$$$

Link to Code

A formal proof or suggestions are appreciated :D

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

who is 54Michael top 1 ?

he wrote only 1 round and already top 1

he also only one who solved task F

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

In problem D, Does anyone have greedy solution, if you have Could you explain me?

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

My clean O(n*k) dp approach for problem D not involving any casework for positive and negative x. Link

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

Problem C: What is reason of this joking telling about mod operation? Which is not necessary yet. Isn't it create confusion about second number can be very large? but actually not

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

Problem C: What's the reason of this modulo joking? It's totally creates confusion about second number can't be very large. But a misleading info

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

jh

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

I can't understand how problem solved for all roots in problem E!?

Is this some kind of trick to solve problem based on solving it for one root (because I know something like this exists) or not, am I missing something?

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

nice

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

Why Awoo and BledDest like casework, Irritating Implementation problems ?