DP on Trees: Tree Distances I

Поділитися
Вставка
  • Опубліковано 29 січ 2025
  • Beginner friendly and clear explanation to the problem cses.fi/proble...
    I recommend trying on your own before you watch the video :)
    Github llink for code: github.com/kar...
    My Codechef profile : www.codechef.c...
    My Codeforces profile : codeforces.com...
    If you found this helpful, like share and subscribe!
    Super useful books for algo ds and programming fundamentals!
    1. Introduction to Algorithms by Cormen: amzn.to/35AmQqu
    2. The Algorithm Design Manual: amzn.to/2K9RGPq
    3. Fundamentals of Data Structures in C++: amzn.to/2LCwIsN
    4. Object-Oriented Programming by E Balagurusamy: amzn.to/2Xxmdtr
    5. Head First Java: amzn.to/39kb44K
    6. Cracking the coding interview: amzn.to/3iDOHLK
    7. Database System concepts: amzn.to/3pisuFQ
    8. Operating Systems: amzn.to/39fcmis
    9. Discrete Mathematics: amzn.to/2MlgCE6
    10. Compiler Design: amzn.to/3pkYvx2

КОМЕНТАРІ • 67

  • @aadityaupadhyay6264
    @aadityaupadhyay6264 3 роки тому +58

    I solved it simply by finding the two endpoints(farthest nodes) and then apply BFS on these two and find the distance from endpoint to other nodes, then our answer is simply max(endpoint1[i],endpoint2[i])

    • @BantiKumar-gd3lr
      @BantiKumar-gd3lr 3 роки тому +1

      do you have any proof for this solution ?

    • @ranjithtevnan2909
      @ranjithtevnan2909 3 роки тому +5

      Oh yeah this is also a brilliant method!

    • @arjunj2125
      @arjunj2125 2 роки тому +4

      @@BantiKumar-gd3lr The proof is same as for why only 2 dfs is required to find the diameter of a tree. Check CodeNCode's video if you aren't able to prove it yourself. Cheers mate

    • @rajkamalingle9144
      @rajkamalingle9144 2 роки тому

      Nice

    • @adityasai550
      @adityasai550 2 роки тому

      @@arjunj2125, I tried this approach and got the wrong answer
      what happened is the two farthest nodes lie on the same path from the root, so I was getting the wrong answer.
      Can you tell how to implement this approach

  • @akshatojha7791
    @akshatojha7791 4 роки тому +13

    Oh good!! What an explanation.
    Superb man, I mean the question was too difficult and you made it look easy.

  • @jatinranpariya1510
    @jatinranpariya1510 Рік тому +2

    Can you explain why the initial call to the solve function have partial answer as -1???

  • @ANANDKUMAR-jk9yp
    @ANANDKUMAR-jk9yp 4 роки тому +2

    Awesome Explanation sirji! Please keep adding such videos!

  • @TheNishant30
    @TheNishant30 6 місяців тому

    Is the choice for node g limited to leaf nodes? because it's partial solution will be 1 and that can be propagated to its adjacent nodes. Partial ans(g/p) will not have to be computed for a leaf node, but for any internal node this wouldn't necessarily be 1.

  • @mayurkoli4145
    @mayurkoli4145 4 роки тому +4

    is it a Re-Rooting technique ?

  • @shivapatel2569
    @shivapatel2569 2 роки тому

    How to propagate the answer downwards in the tree?

  • @alokkumarsingh4641
    @alokkumarsingh4641 10 місяців тому

    is this the same as in out dp?

  • @amandixit3555
    @amandixit3555 3 роки тому

    Hi kartik bahi , orz
    I find difficulty while implementing the solution to medium level problems. How should i strategize so that can imporove that part.

  • @notsodope7227
    @notsodope7227 2 роки тому

    Hey Kartik what is the difference between this and the diameter? There also we were finding diameter of every node same as here?

  • @pleasesirmorevideos4684
    @pleasesirmorevideos4684 4 роки тому +6

    i have this approach like first find the two farthest nodes in the tree let's denote them by A and B. and let's run BFS from both of this and let minimum distance from A for all nodes in the tree be stored in distA and same for B in distB. now for any node if we want to calculate the answer for let's say C. now if you observe very carefully and keep considering the fact that the diameter is from A to B and its length is constaant. only then you will realise that for C answer will be max(distA[C], distB[C]).
    I am pretty sure that what I have said makes sense. Can you confirm this sir? i am too lazy to implement this.

    • @AlgosWithKartik
      @AlgosWithKartik  4 роки тому +3

      I think it's correct, check my DP ON TREES blog on CF there was a similar discussion there i guess.

  • @atishayjain1557
    @atishayjain1557 4 роки тому +3

    Nice explanation!
    I also wanted to know what approach do you take in a situation where you cannot pass certain test cases? Do you dry run the code or are there other parameters as well that you keep in mind?

    • @AlgosWithKartik
      @AlgosWithKartik  4 роки тому +10

      Hi Atishay, normally I would recommend proving your algorithms. If you are able to prove it mathematically then there is no scope left for any testcase to fail. However this is not always practical when we are low on time(coding tests etc) so then I would try coming up with small testcases for which I know the correct answer and see the output produced by my code.
      I suggest you to always try to prove your algorithms when you are practicing this will certainly help you to improve :)

    • @antifest
      @antifest Рік тому

      @@AlgosWithKartik Like how do you prove this exactly?

  • @lilikiki4052
    @lilikiki4052 2 роки тому

    Could you explain ans [src] = line in the end ?

  • @ramgoyal4544
    @ramgoyal4544 Рік тому +2

    Nice Question

  • @parthgupta7317
    @parthgupta7317 4 роки тому

    Very Nice Explanation ! Really made the question look simple

  • @pleasesirmorevideos4684
    @pleasesirmorevideos4684 4 роки тому +1

    Amazing explaination sir.

  • @paragroy5359
    @paragroy5359 4 роки тому

    Nice explanation sir....thanks a lot for such a useful content

  • @saurabhsen3560
    @saurabhsen3560 4 роки тому +1

    I was able to think of the same solution what you discussed but I am facing difficulty in implementation can you suggest me some tips how can I improve I try to implement by myself but in the end, I have to watch your solution

    • @AlgosWithKartik
      @AlgosWithKartik  4 роки тому +3

      Practice practice and practice!
      Try writing modular codes.

  • @AbhishekKumar-be7tx
    @AbhishekKumar-be7tx 3 роки тому

    Why don't we use directed edges only? So that the extra check src != par get resolved?
    I had done that but it's saying wrong answer can anyone tell why?

  • @proton3773
    @proton3773 Рік тому +1

    simpler solution and explanation exists.
    using prefix and suffix just overcomplicates things.

    • @AlgosWithKartik
      @AlgosWithKartik  Рік тому +6

      Yes a simpler solution exists but I find it much harder to prove it's correctness.
      The primary goal for this playlist is to learn how DP can be applied to Tree-like structures which couldn't be learned through the simpler solution.

  • @sangeetamishra2491
    @sangeetamishra2491 4 роки тому +1

    Well explained. Thank you.

  • @shaheensaifi1879
    @shaheensaifi1879 4 роки тому +1

    Best solution

  • @VipinKumar-hr5wy
    @VipinKumar-hr5wy 4 роки тому +1

    Thanks a lot.It was very helpful.

    • @AlgosWithKartik
      @AlgosWithKartik  4 роки тому

      Happy to know you liked it.
      Do share it with your friends too :)

  • @Sagar-uh7zc
    @Sagar-uh7zc 4 роки тому

    Nice explanation 👌👍

  • @ovipoddar2723
    @ovipoddar2723 4 роки тому

    very well explained sir !

  • @kira-nr3qj
    @kira-nr3qj Рік тому

    there is a mistake while writing, it should be 1 + partial_ans(grandparent/parent), it is however correct in code.

  • @sauravjha5666
    @sauravjha5666 3 роки тому +3

    if you solve the question using bfs, it's way easier than this. this is unnecessary overkill.

  • @zyro9922
    @zyro9922 3 роки тому

    I could only think BFS and evaluate depth.... Prefix max sum was really good

  • @yash_______105
    @yash_______105 2 роки тому +1

    To be honest, these questions are easy to understand but implementation is tricky and u r not doing that. (Though it's best content)

  • @MarufHasan-cg6tq
    @MarufHasan-cg6tq 4 роки тому +1

    I think, this is so called In-Out Dp technique.

    • @AlgosWithKartik
      @AlgosWithKartik  4 роки тому +3

      I think it's called the rerooting technique.

    • @MarufHasan-cg6tq
      @MarufHasan-cg6tq 4 роки тому +2

      @@AlgosWithKartik yeah you are right ,
      blogarithms.github.io/articles/2019-10/inout-dp-tree
      I learn from this blog,so that i know this in that name.

    • @AlgosWithKartik
      @AlgosWithKartik  4 роки тому +2

      @@MarufHasan-cg6tq what's in the name anyway :p

  • @crazyboy-gw7rk
    @crazyboy-gw7rk 2 роки тому

    partial ans topic unclear

  • @gentleman7060
    @gentleman7060 2 роки тому

    should have avoid complex coding . See the comments people have done it easier way.

  • @anthorkumardas6498
    @anthorkumardas6498 Рік тому

    You should make a proper plan before making any video. Without any preparation, you're just going nowhere and you even don't know that to make it simple you are making it more complex for your audience to understand.
    So, before creating any video at least think a few minutes and divide the lesson into a few steps. Right down the steps on a notebook. Then try to make the video following those steps. This will make your work more easy and also easier for your audience to understand the lesson.

  • @secretpositron8626
    @secretpositron8626 2 роки тому

    Sirf mujhe hi code smjh nhi aaya ya kisi aur ko bhi (ب_ب)thoda clear samjhaya karo bhaiya confuse hogya end me

  • @PratikDongare-bh2vs
    @PratikDongare-bh2vs 6 місяців тому

    this is how i did it
    vectortree[200001];
    void dfs(int source,int par,vector&dist){
    for(auto it:tree[source]){
    if(it!=par){
    dist[it]=1+dist[source];
    dfs(it,source,dist);
    }
    }
    }
    void solve() {

    ll n;
    cin >> n;
    for (int i = 1; i < n; i++) {
    int x, y;
    cin >> x >> y;
    tree[x].push_back(y);
    tree[y].push_back(x);
    }
    vectordist(n+1,0);
    //did dfs from the 1 to find the longest node from the 1
    dist[1]=0;
    dfs(1,0,dist);
    ll maxi=0;
    int z=1;
    for(int i=1;imaxi){
    maxi=dist[i];
    z=i;
    }
    }
    //did dfs from the longest node to find the other endpoint
    vectordist2(n+1,0);
    dfs(z,0,dist2);
    maxi=0;
    int z1=1;
    for(int i=1;imaxi){
    maxi=dist2[i];
    z1=i;
    }
    }
    vectordist3(n+1,0);
    dfs(z1,0,dist3);

    for(int i=1;i

  • @rishabhkumar8115
    @rishabhkumar8115 2 роки тому

    Thanks a lot.It was very helpful.

  • @rishabhkumar8115
    @rishabhkumar8115 2 роки тому

    Thanks a lot.It was very helpful.