2

Codeforces Round #845 (Div. 2) and ByteRace 2023 Editorial

 1 month ago
source link: https://codeforces.com/blog/entry/111729
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Codeforces Round #845 (Div. 2) and ByteRace 2023 Editorial

Processing math: 32%

We hope you enjoyed the contest!. Thank you for your participation! Do vote under the Feedback section, and feel free to give your review of the problems in the comments.


1777A - Everybody Likes Good Arrays!

Idea: ShivanshJ
Preparation: ShivanshJ
Editorialist: ShivanshJ

Hints
Solution
Implementation (C++)
Implementation (Python)
Feedback

1777B - Emordnilap

Idea: TimeWarp101 quantau
Preparation: TimeWarp101
Editorialist: TimeWarp101

Hints
Solution
Implementation (C++)
Implementation (Python)
Feedback

1777C - Quiz Master

Idea: quantau
Preparation: TimeWarp101 quantau
Editorialist: TimeWarp101

Hints
Solution
Implementation (C++)
Feedback

1777D - Score of a Tree

Idea: AwakeAnay
Preparation: mayankfrost ShivanshJ
Editorialist: AwakeAnay

Hints
Solution
Implementation (C++)
Feedback

1777E - Edge Reverse

Idea: Crocuta
Preparation: mayankfrost
Editorialist: mayankfrost

Hints
Solution
Implementation (C++)
Feedback

1777F - Comfortably Numb

Idea: Crocuta
Preparation: TimeWarp101
Editorialist: Crocuta

Hints
Solution
Implementation (C++)
Feedback

15 months ago, # |

lol didn't read

15 months ago, # |

The time complexity allowed for problem C is too high

  • 15 months ago, # ^ |

    We had initially thought of keeping it tighter but after some discussions we decided that it wont be be a good idea to let n∗A−−√2n∗A2 not pass, but n∗A−−√3n∗A3 pass.

    • 15 months ago, # ^ |

      how to achieve O(n*A^(1/3))?

      • 15 months ago, # ^ |

        The maximum factors of a number AA are bounded by A−−√3A3. Discussion for the same.

        Using some precalculation methods you can store factors for all possible smartness values as nn was capped at 105105. Refer the implementation for the same.

        • 15 months ago, # ^ |

          thanks!

        • 11 months ago, # ^ |

          I do not quite understand this, are you saying that it is possible to enumerate all factors in 3x−−√3x time? Can you tell how?

    • 15 months ago, # ^ |

      Rev. 5  

      -17

      [DELETED]

      • 15 months ago, # ^ |

        The statement clearly say that:

        It is guaranteed that the sum of n over all test cases does not exceed 10^5.

    • 15 months ago, # ^ |

      I passed with time complexity O(nlognA−−√)O(nlog⁡nA).

      • 15 months ago, # ^ |

        I used Segment Tree and passed with time complexity O(128nlogm)O(128nlog⁡m).

        • 15 months ago, # ^ |

          Rev. 3  

          0

          Same, shouldn't have passed, code breaks an test

          100000 100000

          83160 100000 times

          They just didn't include that test, which allowed many wrong submissions to pass, not only segtrees, but also some people used maps, which results in same complexity.

          It is posible to fit this code in TL, the person's above code runs in 2550ms, mine in 2170 ms (without I/O), so with small bit optimizations on segtree I got 2022ms (also without I/O), if improved more, this should pass.

15 months ago, # |

When systesting?

15 months ago, # |

The TL on F is stupidly high, a simple O(n2)O(n2) passed: 190000292

  • 15 months ago, # ^ |

    Hacked

    • 15 months ago, # ^ |

      Optimized it, I wanna know if you could hack this one: 190039238

      Also I think it's kind of wrong that people started downvoting my comment, me being hacked doesn't change the fact that TL is absurdly big when only O(nlognlogA)O(nlognlogA) was intended in the first place.

      • 15 months ago, # ^ |

        what does that "tune=native" do ?

15 months ago, # |

idk why i was stuck on B. I knew the final product needed for the answer, but it was failing pretest 3

  • 15 months ago, # ^ |

    same i dont know why

    • 15 months ago, # ^ |

      If you change n and m to long long it works, i guess because you are combining long long and int you should go for all long long but I´m not completely sure.

      • 15 months ago, # ^ |

        it worked thanks,I read 10^5 as 10^4 in the range of n and tested 10^4 and thought declaring m long long shouldn't be a problem fm.

  • 15 months ago, # ^ |

    I had the same problem as you. When n = 10^5, n*(n-1) overflows an integer. So n also has to be a long long.

15 months ago, # |

The editorial of #845 is earlier than #844

Or there will be no editorial of #844

  • 15 months ago, # ^ |

    Oh please stop spamming everywhere, You have commented in most of the blogs in recrnt months, Instead of spamming go and find some friends to talk with them

    • 15 months ago, # ^ |

      lol, don't assume we have friends.

15 months ago, # |

In problem A,you could just simply check consecutive elements whether they were even or odd.The count of consecutive even or odd pairs or both would be the result._

  • 15 months ago, # ^ |

    Who asked? There is already the solution above.

15 months ago, # |

My solve for C barely passed, 1996 ms. Thought I had to binary search for length.

  • 15 months ago, # ^ |

    Lucky! Can you share your idea?

    • 15 months ago, # ^ |

      Similar to the solve in the tutorial, I kept a frequency of how many factors appeared and I binary searched to what length to keep it. If the length is greater than the series, it fails.

15 months ago, # |

Rev. 3  

0

Any advice on How to master number theory..I Struck in "C" today.(How to think in the mathematical sense for the problem).

15 months ago, # |

can anyone tell me what i did wrong in C?

  • 15 months ago, # ^ |

    Rev. 2  

    0

    Bro,You have to minimize the answer.Which you have notdone.

    • 15 months ago, # ^ |

      I have sorted the smartness array in reverse, so the answer is the maximum value possible for each number,how can i further minimize it?

15 months ago, # |

I managed to hack my own code after the contest, feels bad to get accepted after this...

15 months ago, # |

A good Spring Festival gift, but a stupid me. ):

15 months ago, # |

It's such a pity that I watched the Spring Festival Gala and failed to solve E in time.

15 months ago, # |

In E instead of topological sort, you can just check the in degree of each scc. If there are more than one scc with in degree == 0 then graph is not reachable.

  • 15 months ago, # ^ |

    I'm not sure if I got your point right, but I guess you're saying that if there's more than one node with indegree equal to zero in the scc graph, then there is no answer, if so consider the following test:

    3 2

    1 2 1

    3 2 2

    you can make node one reach every node by reversing the second edge (3 2 2) could you clarify a bit more ?

    • 15 months ago, # ^ |

      No I was talking about the routine inside binary search. You make all edges with weights less than or equal to mid double sided. Then you make SCC and if there are more than one nodes with in degree 0 then not possible for that value of mid.

      • 15 months ago, # ^ |

        Aha it's clear now. Thanks !

15 months ago, # |

There is a right bracket missing in the solution of Problem D. The location is just as the picture shows.

15 months ago, # |

In the contest I wrote such an algorithm below for F: for every index I,find the interval that a_i can be the largest element in any subarray of it,which can be solved simply in O(n) complexity. Then just calculate the answer for every I using 01trie.The total complexity is O($\sum len(interval)$log n). If the value of a_i are distinct,the complexity is O(nlogn),which is acceptable.However,if there are same elements---for example a_i are same for every I,the complexity would be O(n^2) or higher.

However,the algorithm passed both the pretest and the system test.Isn't the data too weak?

  • 15 months ago, # ^ |

    This algorithm could be improved by finding the interval that a_i is the leftest largest element in any subarray.

  • 15 months ago, # ^ |

    I don't understand. Won't that be O(n^2) even when the elements are distinct. Like, consider when the given array is in sorted order.

  • 15 months ago, # ^ |

    • 190017681 is O(n2)O(n2) (and not O(n∗logn)O(n∗logn) even if even if all elements are distinct.
    Simple testcase
    • It's easy to make all elements distinct, just change aiai integer to (ai,i)(ai,i) tuple, although it won't help in this case.

15 months ago, # |

Rev. 4  

+32

To my attitude , it's too standard. If you understand Chinese (or use translation softwares), you can see that the last two problems are just constructed with some standard algorithms(E: https://www.luogu.com.cn/problem/P3387 and F: https://www.luogu.com.cn/problem/P4735) . The fact that they weren't as hard as usual caused the ranking to seem a little strange. And I think if you replace E or F with harder or more interesting problems, then this round will be much better.

15 months ago, # |

Super fast editorials (: And very interesting problems.

15 months ago, # |

Rev. 2  

0

Am I correct in saying the complexity of my solution for C is O(alnm⋅ln(alnm)+m)O(aln⁡m⋅ln⁡(aln⁡m)+m)? It TLEs in 190006029 when I just use a=105a=105 but passes in 190008245 when I use compute up to the max aiai from the input.

15 months ago, # |

I thought about a harder version of problem D during the contest —

At any integer time t>0 , the value of a node becomes the bitwise XOR of the values of all children (all nodes below it) at time t−1.

How to solve this ?

  • 15 months ago, # ^ |

    I'm guessing that the solution would be the exact same. That the node would have a value of 1 approximately half the time. Not sure though :/

    • 15 months ago, # ^ |

      well you could look at it this way that, let say the grandchildren becomes zero, it means they don't affect the children and we go back to the same case as was mentioned in the original question. Now another case is that the value of grandchildren matters , but you can see that the great grand children will become zero 1 step before, leaving children's value to be dependant on the grandchildren only and not the nodes below that. This way we can conclude that the answer would not change and probability of 0 or 1 will still remain (1/2).

      Correct me if I am wrong :)

      • 15 months ago, # ^ |

        I mean, I'm not sure it's EXACTLY the same. You mentioned that after the leaves become 0, the parents of the leaves won't be affected. But if you look at the root of the tree for example, it will still have to deal with the XORs of a lot more values than in the original problem. However I'm pretty sure that the answer would still stay the same, b/c I doubt that the #of descendants that affect the current node matters.

15 months ago, # |

video editorial for Chinese:

BiliBili

15 months ago, # |

Rev. 2  

+24

In problem E we don't even need to check for toposort in SCC, we just need to check the count of indegree, there should be only one element whose indegree should be zero in the SCC

if there are no elements (you graph is not DAG)

and if there are more than one, than you can't reach from one of the elements to other

  • 15 months ago, # ^ |

    Yes. You are right. The editorial is a little off. What we meant was you don't need to do the complete SCC algorithm. You can just do a toposort on the graph (which is the first part of SCC algo). If you think about it,the first node in this sorted list will be the one belonging to a 0-degree SCC. So, you can just check the reachability of all other nodes from the first node.

15 months ago, # |

how can one can generalize this statement "We will focus on computing the expected value of F(A) rather than the sum, as the sum is just 2n×E(F(A))" from editorial of question d.

  • 15 months ago, # ^ |

    Each initial situation has chance of p(A)=1/2^n to appear, so E(F(A))=sum(F(A)*p(A))=sum(F(A)/2^n)=(1/2^n)*sum(F(A)).

15 months ago, # |

Rev. 2  

+8

F can be solved with the standard D&C in less than 1s. why is the TL 8s?

15 months ago, # |

I didn't understand the explanation for D.

  • 15 months ago, # ^ |

    Jumping off someone else's comment, the idea is that if we let V(node, time) be the sum of all the possible values of this node over all initial positions, then V(node, time) is equal to 2^n-1 for all nodes and times(except when we hit a time such that the value of the node is guaranteed to become 0). This is b/c we can expect each node to have a value of 1 approximately half the time. This is kind of intuitive to see, but you might need to do some examples to prove this to yourself. So in order to calculate the sum of all ideal V's, we need another observation. At time 1, the problem states that the leaves of the tree will become 0. This effect will actually cascade upwards. So if a node i has a height of k_i (the distance from the node to the farthest leaf that's a descendant), then that means that it will have a 50% chance to be a 1 for exactly k_i times, before becoming a 0 for the rest of eternity. So the solution is to sum up all the values of k_i and multiply that sum with 2^n-1.

15 months ago, # |

In problem D, the way Vu(A,t)Vu(A,t) is defined (that is, value of node u is bitwise xor of all nodes at distance t from u) is not at all true for t=1, or many instances of time, for ex:

Did I do something wrong or there is something wrong in the editorial?

15 months ago, # |

I didn't understand how we calculate expected value of k boolean nodes in problem D, can someone explain in simpler)

  • 15 months ago, # ^ |

    Expected value = C(k, odd) / (C(k, odd) + C(k, even)). It's a well known fact that C(k, odd) = C(k, even) with k > 0.

    • 15 months ago, # ^ |

      thanks!

15 months ago, # |

Rev. 2  

0

I approached Problem C: Quiz Master in the following way:

Let posxposx store all numbers numnum (present in given sequence AA) such that numnum is divisible by xx. Also make posiposi is sorted for each 1≤i≤m1≤i≤m.

If posiposi is empty for any ii then our answer is −1−1 else it is just a variation of this problem Smallest range in K lists.

Smallest range in K lists

Here is my submission.

15 months ago, # |

emordnilap is palindrome backwards.

15 months ago, # |

For B. Emordnilap, wouldn't you have to set ans to a long long (c++ solution)? N goes up to 10^5 and n * (n-1) would most definitely be past the ranges of an int. an int goes to about 2 billion (2^9 or to be exact 2147483647), and multiplying would be out of the range. Please tell me if I'm wrong.

  • 15 months ago, # ^ |

    3rd line of code:

    #define int long long

15 months ago, # |

For Problem F, the editorial solution gives Memory Limit Exceeded on test 84. https://codeforces.com/contest/1777/submission/190232289

  • 15 months ago, # ^ |

    Can someone please tell me where have I got it wrong?

  • 15 months ago, # ^ |

    That's because you submitted it in a 64 bit compiler. Pointers are 8 bytes in 64 bit compilers and 4 bytes in 32 bit compilers. The solution will pass if you submit it in a 32 bit compiler (like GNU G++17). But it takes double the memory in 64 bit compilers and therefore MLEs.

    • 14 months ago, # ^ |

      Now I know that 64-bit can be harmful too.

15 months ago, # |

Suggestion for people having TLE on F even though they implemented the optimal solution: Make sure you use a structure like a segment tree or sparse table to find the maximum in the interval you are solving. Or alternatively, pass it when returning recursion. Do not iterate through the entire interval as I did as that can take up to O(N2)O(N2) time, because d&c does not divide in half each time.

  • 15 months ago, # ^ |

    Or they could just do the standard D&C which divides in half :)

    • 15 months ago, # ^ |

      How to solve it with standard D&C?

      • 15 months ago, # ^ |

        For a segment [l;r][l;r] let m=(l+r)2m=(l+r)2.

        The optimal answer is either in the left, right or both parts. For the left and right parts solve recursively.

        Now, if the answer lies in the both parts. Assume that a segment [L;R][L;R] such that L≤m<RL≤m<R is the optimal answer.

        max(aL,...,aR)max(aL,...,aR) lies either in the [L;m][L;m] (left part) or [m+1;R][m+1;R] (right part).

        Let's assume that it's in the right part. We will use two pointers. Initially, L=mL=m and R=m+1R=m+1

        Assume that the right end of the answer is RR. We already know the maximum element mxRmxR and xor xrRxrR of the right part.

        We have the right part of the answer, but we are missing the left one. How do we find it fast such that it would be the optimal one?

        We assumed that the maximum element in the optimal answer lies in the right part. It means that each segment [L;m][L;m] such that max(aL,...,am)≤mxRmax(aL,...,am)≤mxR combined with the right part could be the optimal answer.

        Create a trie for xor.

        While max(aL,...,am)≤mxRmax(aL,...,am)≤mxR, add xor(aL,...,am)xor(aL,...,am) to the trie, and decrease LL.

        When you can't move LL anymore, get the best number xrLxrL from the trie to maximize mxR⊕xrR⊕xrLmxR⊕xrR⊕xrL and update the answer.

        When you are done, repeat the process for the left part(as if the max would be in there).

        submission

        • 15 months ago, # ^ |

          I think that I understand your solution. It seems like O(N^2), but it actually has O(N log A) armortized complexity per division. Thank you for sharing.

          • 15 months ago, # ^ |

            The complexity is O(nlogn∗logn)O(nlogn∗logn).

            Btw, why does it look like an O(n2)O(n2) algo? It is absolutely the same as the standard D&C with an additional log from the trie?

            • 15 months ago, # ^ |

              I mean the solution which first comes to mind seems like you would need to do O(N2)O(N2), because of keeping maximum and stuff. (Like, going through all possible right and left borders) But actually, it's enough to move one border and move the other one only when necessary by fixing on which side maximum is.

15 months ago, # |

problem B was just super good.Idea of solving it is just amazing.

15 months ago, # |

It's a bit too much talking about SCCs and kosaraju for E when in the end it just comes down to topologically sorting the uncondensed graph to find an appropriate candidate. But knowing how to think it terms of SSCs does help in this kind of problem.

  • 15 months ago, # ^ |

    No, you need to do topological sort on the condensed graph.

    • 15 months ago, # ^ |

      If what you call the condensed graph is the one with nodes being SCCs, then you definitely don't. you can check my submission for example. I use binary search. To verify a given cost cc, I consider the graph with reverse edges only if c≤wc≤w. I only topo sort then do a dfs on the untransformed graph starting from the top/root node i get. This is because topo sort guarantees that if the "root" node can't reach another node, then this node can't reach the root node either.

      Of course it's true for whatever node nini that appears before node njnj in the topological sorting.

      • 15 months ago, # ^ |

        Rev. 2  

        +1

        That’s an interesting solution. I didn’t think that you can do that. However, I believe that the SCC solution is actually straightforward for most people.

15 months ago, # |

Hey I find this Round has become unrated.Does anyone know why?

  • 15 months ago, # ^ |

    I was about to write the same; did you get any answers ???

    • 14 months ago, # ^ |

      Rev. 2  

      0

      Maybe unrated all the time?

15 months ago, # |

What E(F(A)) means?

14 months ago, # |

Don't understand why they prefer to put something like calculating things about max(al,⋯,ar)max(al,⋯,ar) to the last problem. You can solve most of this kind of problem using divide and conquer, or play dsu on cartesian tree. It's very typical and you can see many similar solutions in other problems about min max. With this trick, I figured out F in ten minutes with E still unsolved. (Actually I worked on D for 40 minutes after the contest) I also passed an Ex in ABC easily with this idea.

6 months ago, # |

@TimeWarp101

In problem C,

why sorting is gonna help?

14 hours ago, # |

Rev. 2  

0

as a beginner problem a was fun solving

4 hours ago, # |

Cant figure out why this code is not working for Problem C. Any help is appreciated!

include<bits/stdc++.h>

using namespace std;

define pb push_back

define all(c) (c).begin(),c.end()

define fi first

define se second

typedef long long ll; typedef vector vi; typedef vector vvi; typedef vector vl; typedef pair<int,int> pi;

const int mxN = 1e5; vi facs[mxN+1]; int freq[mxN+1]; int cnt,m;

void init() { for(int i=1; i<=mxN; i++) for(int j=i+i; j<=mxN; j+=i) facs[j].pb(i); for(int i=1; i<=mxN; i++) facs[i].pb(i); }

void add(int x) { for(int fac : facs[x]) { if(fac>m) break;

freq[fac]++;
    if(freq[fac]==1) cnt++;
}

int sub(int x) { int res = cnt;

for(int fac : facs[x])
{
    if(fac>m) break;

    int t = freq[fac]-1;
    if(!t) res--;
}

return res;

void solve() { int n; cin>>n>>m;

for(int i=1; i<=m; i++) freq[i] = 0;
cnt = 0;

vi a(n); for(int &i : a)cin>>i;
sort(all(a));

int l = 0;
int res = 1e9;

for(int r=0; r<n; r++)
{
    add(a[r]);
    if(cnt>=m) res = min(res,a[r]-a[l]);

    if(l==r) continue;

    int temp = sub(a[l]);

    while(temp>=m)
    {
        cnt = temp;

        for(int fac : facs[l])
        {
            if(fac>m) break;
            freq[fac]--;
        }

        l++;
        res = min(res,a[r]-a[l]);

        if(l==r) break;
        temp = sub(a[l]);
    }
}

if(res==1e9) cout << "-1\n";
else cout << res << "\n";

int main() { ios_base::sync_with_stdio(false); cin.tie(0);

// const char* input_f = ".in";
// const char* output_f = ".out";

// freopen(input_f, "r", stdin);
// freopen(output_f, "w", stdout);
init();
int tt; cin>>tt; while(tt--)solve();
return 0;

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK