SecondThread's blog

By SecondThread, history, 4 years ago, In English

Algorithms Thread Episode 8: Tree Basics

Episode 8 of Algorithms Thread comes out in <90 minutes! This one is a bit more beginner-friendly and covers the following ideas:

  • Graph/Tree Diameters
  • Binary Lifting
  • Tree Flattening with Euler tours

Also, to make sure you have actually learned that stuff, I made a custom Gym set on CodeForces that will last two weeks that hopefully is really good practice for making sure you have learned this stuff. Here is a link to the gym set; it will be available 45 minutes after the video comes out so that people have time to watch the video before starting the set, if they are interested in penalty points. All of the problems in the gym are original to this set (in their flavortext at least, some are simple enough that I'm sure they have appeared in other contests before).

The new gym integration was heavily inspired by Errichto's Matrix Expo set format. Let me know whether it's helpful. I think it might be, but also it's a pretty big time commitment to make it, so whether I keep doing them depends on how helpful they are to people.

If you have any questions or suggestions, feel free to leave them below. I hope you enjoy the problem statements, and I'll leave you all with this:


Solutions

Update:

  • Vote: I like it
  • +1924
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it +50 Vote: I do not like it

Really appreciate your effort for helping beginners to learn new concepts and improve!

»
4 years ago, # |
  Vote: I like it -7 Vote: I do not like it

Looking forward to it!

»
4 years ago, # |
  Vote: I like it +66 Vote: I do not like it
  • »
    »
    4 years ago, # ^ |
      Vote: I like it +54 Vote: I do not like it

    Hey, I understand that you want to make a point, but don't you think tagging them is unnecessary? I believe noone likes to be tagged just to see random people being orzed.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +225 Vote: I do not like it

      Guys, please listen to Ari, don't tag anyone unnecessarily.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it -47 Vote: I do not like it

        Stop tagging Ari, She doesn't like it

        • »
          »
          »
          »
          »
          4 years ago, # ^ |
            Vote: I like it +60 Vote: I do not like it

          Hey, I understand that you guys want to make a point, but don't you think tagging Ari is unnecessary? I believe no one likes to be tagged just to see themselves being joked about by random people.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it -10 Vote: I do not like it

      I fully support condemnation of this practice. Looking at a notification just to see myself being tagged unnecessarily by random people is sure to be tiring.

      In this case, however, I do not think it is a harm. It is a blog written by the "orzed" person, and he (assumingly) reads and enjoys comments here.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +211 Vote: I do not like it

      No, no, why are you saying this? I'm pretty sure that neugis tagged me for a really good reason.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +64 Vote: I do not like it

      Or SecondThreaded

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +184 Vote: I do not like it

      For the record, I like being pinged so that I know when people are talking about me. At least, I certainly don't mind.

»
4 years ago, # |
  Vote: I like it +104 Vote: I do not like it

Wait..... How come this is on the frontpage of CF?

»
4 years ago, # |
  Vote: I like it +4 Vote: I do not like it

Errichto and Thread are changing the learning game istg.

»
4 years ago, # |
  Vote: I like it +94 Vote: I do not like it

At this point, since everything's already prepared for it, they might as well add your stuff to EDU

»
4 years ago, # |
  Vote: I like it +198 Vote: I do not like it
Spreading CP knowledge!
Screenshot-from-2020-08-17-01-07-07
  • »
    »
    4 years ago, # ^ |
      Vote: I like it +22 Vote: I do not like it

    What is the problem with Codeforces EDU? I enjoyed all of their lessons so far. They are all doing a great job. No need to compare 3 great resources.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +6 Vote: I do not like it

      I'm not criticizing EDU or saying it's inferior to others.

      I'm talking about the quantity of videos/resources or more like time taken to make new educational videos.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +341 Vote: I do not like it

    Fortunately, it's not a competition. It's more like we push one racing car together (because the community gets the sum of all resources).

    Also, there are people like Mike or awoo who actually do significantly more, it's just not in form of videos.

»
4 years ago, # |
  Vote: I like it +10 Vote: I do not like it

Thanks, we will try our best to learn new and interesting concepts.

»
4 years ago, # |
  Vote: I like it +11 Vote: I do not like it

Loved the new format ! This helps gain much more confidence in the covered than just watching a tutorial on some topic and not getting custom problems on that topic.

»
4 years ago, # |
  Vote: I like it +4 Vote: I do not like it

Thanks, that’s exactly what I need.

»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

The gym problems are very nice for reaffirming one's understanding of tree basics!

For problem D, what was the offline solution you had in mind? The text at the top implies that there exists an offline solution that's simpler than the online solution, but the only thing I could think of is some wack dfs + segtree solution where you update the answer for a query whenever you reach one of its endpoints. That seems way too complicated to warrant explicitly disallowing offline solutions lol.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +18 Vote: I do not like it

    Yeah it's definitely harder to do offline than online. I was also considering at a small-to-big + dfs with a treeset/segtree which I'm pretty sure is possible and can be done in n*log^2(n) without too much difficulty. The main thing is that this might show up as a sub-problem that you have to answer online, so it's good to be able to do that, rather than finding some complex way that ACs but doesn't actually use the new topics at all.

»
4 years ago, # |
  Vote: I like it +11 Vote: I do not like it

I really love your content

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Your screencast(s) are really helpful.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Please give any hints for second problem.

»
4 years ago, # |
  Vote: I like it +21 Vote: I do not like it

Dear SecondThread,

Thank you for all the hard work you put in daily! Know that it is recognized and greatly appreciated, It’s an honor for our codeforces community to have someone like you.

May you reach every height of success!

»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Hey nice video,

In the tree shown at 36:11, how can I find the sum over the path starting at the node with input time 3 and the node with input time 13? I can think of a way to do it but it requires calculating LCA of the endpoints, is there a way to do it without LCA?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +15 Vote: I do not like it

    Thanks! Correct, if you need to find some path aggregate in which one node isn’t an ancestor of another, you need to split it into two paths using LCA. (Unless there is some other more clever way that I’m not aware of)

»
4 years ago, # |
  Vote: I like it +3 Vote: I do not like it

Can Someone Explain the Samples of Problem F Please

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    Yeah, maybe part of it isn't super clear: for each query where x = 0, you can consider pairing things however you want just before for that query. These pairings aren't permanent, they are just considerations for that query. The way of making the pairings is to do minimize the sum of distances between every pair of paired seeds/pots.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

expecting more and more from all of you

thanks SecondThread

»
4 years ago, # |
  Vote: I like it +8 Vote: I do not like it

The gym-set along with the usual videos format is indeed really nice. Thank you for your hard work.

»
4 years ago, # |
  Vote: I like it -17 Vote: I do not like it

I've just failed my math exam because of secondthread, he says that pi = 3 in 102694A - Circumference of a Tree, so I used pi = 3 to calculate the volume of a sphere and I got 0 marks on that problem. Guys, don't trust secondthread.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +28 Vote: I do not like it

    Clearly the teacher's solution is wrong then. I have an elegant proof that pi is equal to 3, but it's too long to fit in the margin of this comment thread.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

A bit off topic, but can we expect a video on round 1 problems of hackercup, SecondThread ?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +10 Vote: I do not like it

    He said he won't be taking part in hacker cup in one of his streams.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      I think...he said something along the lines that he wasn't sure if would be allowed to....but I might be wrong...

      Also, I found a comment on youtube...where he answered it so I guess that's it for this thread! (which is a cool line that I am hoping will catch on...lol)

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +11 Vote: I do not like it

    I’m not allowed to compete in hackercup, so probably not from me. I know Errichto has videos of him solving them, and there are some nice solutions on the Hacker cup website, too.

»
4 years ago, # |
Rev. 7   Vote: I like it 0 Vote: I do not like it

Hey guys, I am bit stuck on prblem B, my approach was:

  • start from arbitary node and find the farthest node, call it 'root'
  • from 'root' , do a bfs and find the distance of all other nodes
  • The maximum distance now will be the diameter,now,
  • If distance of some node from 'root' is same as diameter or zero, the answer for this will be diameter+1 , else the answer for this node will be same as diameter

I am getting a wrong answer on test 6. Can someone plz help?

Any general tips to debug will also be appreciated.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    There can be multiple "root". Take care of that also

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      I took care for that. I tried DFS from any general node..got all the max distant nodes.. Then ran a dfs from all of them to get their end points...of maxDiam..

      Then simply checked if for i is it in the stored points..I added diam+1 as asnwer..else diam is answer.

      Getting TLE for TC4 https://codeforces.net/gym/102694/submission/90401537

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Make sure you dont linearly check, probably some faster way

        Spoiler
        • »
          »
          »
          »
          »
          4 years ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          I didn't get the spoiler hint..It would be great if you could eleborate with some another example which could relate things up.

          As I got that searching linearningly for N nodes would difinately be TLE...

          • »
            »
            »
            »
            »
            »
            4 years ago, # ^ |
              Vote: I like it 0 Vote: I do not like it

            Find the boundary points. Think of a better way than a linear search.

            Spoiler
            • »
              »
              »
              »
              »
              »
              »
              4 years ago, # ^ |
                Vote: I like it 0 Vote: I do not like it

              There is little confusion. I am using Set for finding the elements if the element is end point of diameter. The only linear part I am doing is with find function which calculates the dep and diam initially.

              • »
                »
                »
                »
                »
                »
                »
                »
                4 years ago, # ^ |
                  Vote: I like it +3 Vote: I do not like it

                Yeah, that's not the intended solution at all. There shouldn't be any need for a log factor here.

                Spoiler
  • »
    »
    4 years ago, # ^ |
    Rev. 5   Vote: I like it +3 Vote: I do not like it

    What if the tree is like this?

    Tree

    From node 1 you will find 7 (or 8) as the farthest node. And then from 7 (or 8) you will find 1 as the only farthest node. The problem is that your algorithm will consider only 1 and 7 (or 1 and 8) as all the possible nodes which should increase the diameter by 1, but actually all of them will increase it (1, 7, 8). You can try this example yourself for more details.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Hey Brodicico! Could you(or anyone) please tell me what mistake I am making. (I am continuously getting WA on test 5 and I am unable to figure out what mistake I am making — whether it is the implementation or the logic)

      LOGIC :
      CODE :

      A counter test case with its correct output is highly appreciated.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Try a case where you have a tree in a chain form like 1-2-3-4-5-6-7-8-9. Then connect node 10 with vertex 5.

        The tree will be :

        1-2-3-4-5-6-7-8-9
                |
                10
        

        For node 10 it isn't correct to output diam+1.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      bro i am getting correct answer for this one but still my code fails no 4th test case

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    There's a hint in the video..watch it again....

»
4 years ago, # |
  Vote: I like it +10 Vote: I do not like it

This was a wonderful effort . can anyone give me the link for other episodes.

»
4 years ago, # |
  Vote: I like it +3 Vote: I do not like it

Your screencast are really helpful. Thank You!

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

1006E - Military Problem
Great problem on one of the concepts explained in the video. Highly recommend it!

My solution for reference: 90223865

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Someone give me a hint on E, please

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +11 Vote: I do not like it

    I tried to find the topological order and size of each subtree. Then did used segment tree for updating and range queries. But it fails in test 4. Any idea guys?

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Overflow issues .. Even i am not getting how to do that .

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +3 Vote: I do not like it

        Maybe we should divide all node values by 10^6 and then build ST on doubles? If product on subttee is bigger then 1000, print 100000000, else print result

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +17 Vote: I do not like it
        Spoiler
        • »
          »
          »
          »
          »
          4 years ago, # ^ |
          Rev. 2   Vote: I like it 0 Vote: I do not like it

          thank you so much!!! it worked!!! you are amazing

          • »
            »
            »
            »
            »
            »
            4 years ago, # ^ |
              Vote: I like it 0 Vote: I do not like it

            How did you deal with log and pow function precision issues??

            • »
              »
              »
              »
              »
              »
              »
              4 years ago, # ^ |
                Vote: I like it +6 Vote: I do not like it

              There were no issues for me with pow and log2. Code

»
4 years ago, # |
  Vote: I like it +10 Vote: I do not like it

As a beginner, your episode has really taught me a lot about the many application of trees. Thanks a ton for this!

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Hey can someone recommend a good list of problems which contains different( hopefully all theory) types of problems on graphs and/or trees....It would be much appreciated....

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

can someone help me , I am getting memory limit exceeded in B. https://paste.ubuntu.com/p/6B8kdrvkyh/

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Hey buddy, I saw your code, actually I think you can simplify the structure itself. Also the variable parent can be avoided, vis can be made boolean. Have you checked if the bfs doesn't explodes the queue?

    • »
      »
      »
      4 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      I made vis boolean , now i getting tle. thanks man ,Changing the structure now. changed endl to "\n" got accepted.

      • »
        »
        »
        »
        4 years ago, # ^ |
        Rev. 2   Vote: I like it 0 Vote: I do not like it

        Didn't know "\n" could change a whole lot of things. Followed some blogs on CF on this. Finally got AC after all the TLEs.

        • »
          »
          »
          »
          »
          4 years ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          The thing is that endl flush the output and that is slow...

»
4 years ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

SecondThread

Any idea for D. Till now , this is how I am going: ( I guess m is always n-1).

  • we need to find the minimum valued edge between sources and destination of the flow network, (as its a tree <or I am wrong here?> and only one path is present between any two nodes).
  • we can do this by storing values of minimum for 1,2,4,8,16.. jumps above for each node, and find them just like we build the jump array in binary lifting.
  • Now we can move to the lca and keep calculating the minimum along both souces to lca and destination to lca, again using the binary lift technique.

Am I going the right way ? ( Wrong answer on 6)

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +13 Vote: I do not like it

    I do actually have an idea of how to solve D, yeah. Your general approach seems right, but I’m not going to discuss solution details too in depth for a week or so.

»
4 years ago, # |
  Vote: I like it +9 Vote: I do not like it

Someone give me a hint on F, please

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

My 2-dfs calls in B is receiving TLE, is it expected ?

»
4 years ago, # |
  Vote: I like it +6 Vote: I do not like it

My code for problem B https://ideone.com/dd5gOx with poor English commentary :)

»
4 years ago, # |
Rev. 2   Vote: I like it +4 Vote: I do not like it

Math burned me, yet again!!

SecondThread

For E the products can be as large as 10^500000 ( that is ((10^5)^(10^5)) ) and we have to store approx 10^6 of those.....how can it be done....can I get a hint?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    you can use logarithm to store the values, and then restore the value with a power of 2

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Wouldn't we loose precision? Can you plz elaborate...?

»
4 years ago, # |
  Vote: I like it +8 Vote: I do not like it

The problems are really, really good. Even if they use basic concepts they were not actually so easy (at least for me). I found the fifth problem very cool and challenging if you don't have experience using mathematical functions (I didn't until this problem :D). I give all my respects to the creator of this problemset. Thanks for investing your time in helping others.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

For question C the code is running on my computer btt it shows runtime error for test case 3

90309168

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    since contest is running, nobody can open the link you posted. Also since test case 3 is visible you can directly debug in local environment to find reason for RE.just use gdb/lldb to step through code.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      test case 3 is running in my local env just fine. btt it shows runtime error whwn i submit.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I haven't registered yet does that mean i'll have to wait for next 12 days?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it
Image:

Hello, i am currently at problem E and i dont understand how does it is not 1.5 in the second example, at the second line.

Since it is 1-rooted, 1 has value 3, 2 has value 2 and 3 has value 1 , no ??? what did i missed here ??

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    In the second sample, none of the nodes are ever updated, so all nodes have a value of 1. (Since the product of 1*1*1... is 1)

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Could anyone please help me with problem E?How to handle such big numbers?

»
4 years ago, # |
  Vote: I like it +13 Vote: I do not like it

I realy enjoy E, although I've made 17 WA.

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Can someone tell me why bfs doesn't work in promlem A to calculate the diameter. It is giving me tle.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    It worked for me, maybe because you're using python and the time is a little tight, try reading this blog to speed up the input and the output. If it doesnt work to you, maybe trying with c++ will be a better way, because I see that the few persons that got AC, their execution time is around to 900ms

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Hi, this is my first time solving Tree based problems on CF. I am having trouble understanding how to give the edges so that I can construct a tree. For example in the first question, the test case is

3

3 2

2 1

How will we construct a tree with 3,2 as edges and which node will they belong to? How will we construct a tree with this? I have seen some other solutions using arrays but i can't understand them.

Leetcode does it like this-

struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

I have previously solved on LeetCode where we had to just write the function so I am very new to this.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +4 Vote: I do not like it

    The one you are constructing in LeetCode is Binary Tree having almost 2 children.

    Here you need to use Adjacency list, which can be implemented via vectors in C++. You should read about it.

»
4 years ago, # |
  Vote: I like it +3 Vote: I do not like it

Any hint for problem F? (getting wrong answer)

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it
    Spoiler
»
4 years ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

Thank you very much for this effort. I really liked the problems.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I solved F by observing some examples, can somebody give proof for F, why this works?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    if you supposed a minimal matching where there are only two nodes on each side , and you paired each node with the one in opposite side you'll find that you can minimize more the distances by pairing each node with the one on it's side.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      "you can minimize more the distances by pairing each node with the one on its side."

      I am looking for why this is always true. Maybe here it is easy to observe.

      • »
        »
        »
        »
        4 years ago, # ^ |
        Rev. 2   Vote: I like it +3 Vote: I do not like it

        Consider the graph: 1-2, 2-3, 2-4

        Node 1 and node 3 have one seed each. Let us consider that there is a pot in the subtree of node 4 (let's call this node A) and a pot in the rest part of the tree above of the node 1 (let's call this node B).

        Optimal solution is to match seed-3 with pot-A and seed-1 with pot-B, because the sum of distances is equal to dist(3, 2) + dist(2, A) + dist(1, B). If you try to "cross" the edge (1-2) and match the seeds in a different way, then the sum would be equal to dist(3, 2) + dist(2, 1) + dist(1, B) + dist(1, 2) + dist(2, A) which is larger than before by 2 * dist(1, 2).

        As you can see, you can never avoid some distances, so there is no reason to try to match a seed with an other pot when there is already one available in its subtree.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I'm failing to understand the input test cases in problem F, where queries are :

    1 6 2
    2 5 3
    4 3 0
    

    Above, 2 seeds at node 1 and 2 pots at node 6 make 2 valid pairs(path 2->6 goes through edge 3-4). Similarly, 3 seeds at node 2 and 3 pots at 5 make 3 valid pairs. This path goes through edge 3-4. This makes a total of 5 valid pairs.

    6 2 2
    4 3 0
    

    Similarly, 2 seeds at node 6 and 2 pots at node 2 make 2 valid pairs and this path connecting 2 and 6 also cross the edge 4-3. So, total of 5+2=7 valid pairs. But, why is the answer for that query 3?

    I'm missing something here, kindly help!!

    Also, it's written The total sum of the distances between every pair must be minimized to keep clean the air. Does this mean something? I didn't get it.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it
      • It's not required that seeds should placed in the respective same pots which were created while creating seeds in each query.

      • In the above example for the last query we can use 2 pots at node 2 for placing seeds from node 1 or 2.

      The total sum of the distances between every pair must be minimized to keep clean the air

      This means that sum distance travelled by each seed from the source node to node which contains pot should be minimized.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Will all the test cases be made public after the contest ends?

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

I am getting TLE in TC 4. I stretched the tree along the diameter and after that if node is added to the end points of diameter then dynamic diameter will increase by 1 otherwise not. My solution is here. Please somebody tell me error in my approach.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

1 sec time limit is pretty rough for java?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    For which problem? I think all the judge solutions are in Java, but I can bump it up if it’s too tight.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      For B, i feel like my sol would pass with 2 sec limit, but if not that is fine, I can move on

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Can someone please explain me what's wrong in my logic for B ? I seem to be repeatedly failing test case #6.

Logic
  • »
    »
    4 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    This will not give you the correct answer.

    Spoiler
»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Can anyone pls provide some test case for problem C? im getting WA on test 4

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I am also stuck on test case 4 with problem C

    • »
      »
      »
      4 years ago, # ^ |
      Rev. 3   Vote: I like it 0 Vote: I do not like it

      SecondThread any hints?

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        I'm not sure if it helps, but I recommend you take a look at the cp-algorithms.com lca tutorial if you're stuck.

        • »
          »
          »
          »
          »
          4 years ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          silverfish No I know about lca and other algorithm to solve it. It is just there must be a corner case that I am missing. Hence wanted some hints

          • »
            »
            »
            »
            »
            »
            4 years ago, # ^ |
            Rev. 3   Vote: I like it 0 Vote: I do not like it

            Kush.code Can you link your code?

            Most likely your logic for calculating c'th node on the path from a to b is wrong. Key is to use LCA to determine whether c'th node is from path (A -> LCA) or (LCA -> B).

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Draw a tree and make all possible cases for k, that's all you need to do.

»
4 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

In question no C these are the arrays in my programm my code is runnig is fine in my system btt shws runtime error when i submit can this be a memory issue??

int N, D;
int depth[300010];//depth of node
vector<int> adj[300010];
int par[20][300010];//binary lifting table

Inside main

    memset(depth, 0, sizeof(depth));
    for (int i = 0; i < 300010; i++)
    {
        adj[i].clear();
    }
    memset(par, -1, sizeof(par));
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

SecondThread, what's the constraint of q in D?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    Oh, good question. I’m pretty sure it’s 3*10^5. But like, answer each query in sublinear time please and you should be good to go.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Thank you very much for the problemset, it's very helpful! I like how it's not just straightforward "implement LCA and be done with it", but includes some modification that forces you to understand the concept behind it.

I have a question about F. It seems that the observation is

Spoiler

Which seems intuitively true, but how to prove it?

  • »
    »
    4 years ago, # ^ |
    Rev. 2   Vote: I like it +3 Vote: I do not like it
    Spoiler
    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Can i get a hint for problem F.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +12 Vote: I do not like it

        The problem is strictly linked with the idea of minimizing the sum of distances between seeds and pots, thus the first thing to think is "when is it necessary to cross edge $$$E$$$ when matching a seed with a pot?".

        This is not likely a hint, but let's try to see something intuitively in the following cases:

          R -> root.
         / \
        P   S
        

        Here you have a pot and a seed in the leaf nodes, thus the result in any edge would be 1 since there's no other matching possible/closer/minimum. This would give us a total sum of 2.

               __R__          -> root.
             /       \
            N1        N2      -> nodes.
          /  \       /  \
        2*P  1*S   1*P  2*S   -> amount of seeds/pots.
        N3   N4    N5   N6    -> nodes.
        

        Here our options would be:

        • Match all pots from $$$N3$$$ with all seeds in $$$N6$$$ and the seed in $$$N4$$$ with the pot in $$$N5$$$. This would give us a total distance sum of 4*2 + 4*1 = 12 and the following edge values:
             __R__         -> root.
           3/     \3       -> edge values.
           N1      N2      -> nodes.
         2/  \1  1/  \2    -> edge values.
        N3   N4  N5   N6   -> nodes.
        
        • Another option would be to match 1 pot from $$$N3$$$ with the seed in $$$N4$$$, the remaining pot from $$$N3$$$ with a seed in $$$N6$$$, the pot from $$$N5$$$ with the remaining seed in $$$N6$$$. This would give us an smaller total distance sum of 2*1 + 4*1 + 2*1 = 8 and the following edge values:
             __R__         -> root.
           1/     \1       -> edge values.
           N1      N2      -> nodes.
         2/  \1  1/  \2    -> edge values.
        N3   N4  N5   N6   -> nodes.
        

        Note that the second option is better because we don't need to cross the root edges multiple (extra) times. Thus, matching seeds/pots locally (closer matches) might reduce the total sum. Also, looking at the last example, try to answer the question "when is it necessary to cross edge $$$E$$$ when matching seeds and pots?" thinking locally.

        After solving (or if you still can't solve) the problem look at the spoilers on this thread to clear any doubt.

        • »
          »
          »
          »
          »
          4 years ago, # ^ |
          Rev. 2   Vote: I like it +6 Vote: I do not like it

          Thanks bro for your effort, I think i got the key now.

          My Idea
          UPD: Solved!, Thank you bro.
          
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I am not able to solve circumference of tree problem .. also there is no editorial available .. what to do ?

»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

It's really helpful! Thank you !

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Can some one plz provide a link to their submission for E. I have understood the approach (partially), but having problem to implement it.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Great video, thank you!

Also, I think a thing worth mentioning is that segment trees can be directly utilized on incomplete rooted binary trees, while this tree -> Euler path -> segment tree approach helps us reduce the complexity when trees aren't necessarily binary.

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

In problem E SecondThread, I got 4 WA's using Fenwick/BIT Tree but as soon as I changed it to Segment Tress, it got accepted.

Solution using BIT/Fenwick Tree

Solution using Segment Tree

I am unable to understand why it is happening. If anyone has solved this question using fenwick tree, please look at the code and tell where is it going wrong or share your code.

UPD: I got the error. I was constructing the fenwick tree in a wrong manner.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Hmm, my model solution uses a fenwick tree. That’s odd for sure...

    • »
      »
      »
      4 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      If that's so, then I must be doing some silly/ gross mistake that I am unable to find. I hope you wouldn't mind to taking a peek at my code unless you're busy.

      Anyway, thanks for the clarification.

      UPD: I got the error, I was construting the Fenwick Tree in a wrong way.

»
4 years ago, # |
  Vote: I like it +9 Vote: I do not like it

Nice guide, really appreciated.

For everyone looking for other problems to apply the tree flattening trick, here are some from CSES problem set:

»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Can someone please let me know why My code fails on test 5(Problem B)

code

»
4 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

For problem C: Assume tree like following.

7
1 2
1 3
2 6
2 7
3 4
3 5
2
7 5 1
7 5 3

Is the answer (2, 1) or (2, 3)?

»
4 years ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

Can anyone tell me why I am getting the wrong answer for testcase-4 in problem E, or give me any test case? SecondThread

code

»
4 years ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

Can i get hint for problem F.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Can someone please explain me the way to approach problem F.I have been stuck at it for quite some time now !!

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

can anyone tell how to do c

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

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

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Really enjoyed thanks.

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

SecondThreads java solutions were posted, but if you need A-E in c++: A B C D E F

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

I'm facing a weird error. The same solution is getting accepted in C++14 and getting RE in C++17 for Problem B.

Accepted code

Same code is getting RE in C++17, I tried
1. using memset for dist arrays
2.return 0 for main fn

SecondThread What could be the problem?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    That sounds more like a C++ issue to me than anything else. If I had to guess, I would say it's likely a stack-space configuration issue. I think the RTE is probably that your recursion goes too deep on the rope case for instance, which causes you to run out of stack space.

    I don't know what differences there would be otherwise, although I was under the impression that your main was always suppose to return 0...

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

SecondThread the problems aren't available in the gym contest

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

SecondThread if possible, maybe u can link the video editorial as editorial in the problemset. That may help a little bit

»
8 months ago, # |
  Vote: I like it 0 Vote: I do not like it

249461942 can someone please help for 102694B - Dynamic Diameter why is this failing for test case 6?

  • »
    »
    4 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I think it would fail for a graph like this: 1-0 2-0 3-0 0-4 4-5 5-6 6-7 6-8 6-9

»
4 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Wow this is super good. The explanation video is great, the problems are super, really appreciate it!

»
5 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

285451412

i am stuck in problem 1 getting TLE , can't figure out why

HERE'S MY CODE as submissions of other people might not be visible

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;

public class A102694 {
    static int[] max = new int[2];

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        ArrayList<ArrayList<Integer>> tree = new ArrayList<>();

        for (int i = 0; i <= n; i++) {
            tree.add(new ArrayList<>());
        }

        for (int i = 0; i < n - 1; i++) {
            int a = sc.nextInt();
            int b = sc.nextInt();
            tree.get(a).add(b);
            tree.get(b).add(a);
        }

        int ans[] = bfs(tree, 1, n);

        System.out.println(3 * bfs(tree, ans[0], n)[1]);

        sc.close();
    }

    public static int[] bfs(ArrayList<ArrayList<Integer>> tree, int start, int n) {
        HashSet<Integer> visited = new HashSet<>();
        int dis[] = new int[n + 1];

        ArrayDeque<Integer> queue = new ArrayDeque<>();

        queue.add(start);

        while (!queue.isEmpty()) {

            int head = queue.poll();
            for (Integer i : tree.get(head)) {
                if (visited.contains(i)) {
                    continue;
                }
                queue.add(i);
                visited.add(i);
                dis[i] = dis[head] + 1;
            }

        }

        int ans[] = new int[2];

        for (int i = 1; i < dis.length; i++) {
            if (dis[i] > ans[1]) {
                ans[0] = i;
                ans[1] = dis[i];
            }
        }

        return ans;

    }
}