RainX_69

FIND MINIMUM LIGHT BULBS TO SATISFY (HARD TREE PROBLEM)

Jan 30th, 2023
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | Source Code | 0 0
  1. https://practice.geeksforgeeks.org/problems/f7bfa137576243795abb0595962d61b632bbad21/1
  2.  
  3. Given N nodes of a tree and a list of edges. Find the minimum number of nodes to be selected to light up all the edges of the tree.
  4. An edge lights up when at least one node at the end of the edge is selected.
  5.  
  6. Example 1:
  7. Input:
  8. N = 6
  9. edges[] = {(1,2), (1,3), (2,4), (3,5), (3,6)}
  10. Output: 2
  11. Explanation: Selecting nodes 2 and 3 lights
  12. up all the edges.
  13.  
  14. Example 2:
  15. Input:
  16. N = 3
  17. arr[] = {(1,2), (1,3)}
  18. Output: 1
  19. Explanation: Selecting Node 1
  20. lights up all the edges.
  21.  
  22. ---------------------------------------------------------------------------------------------------------------------------------------
  23.  
  24. class Solution{
  25.   private:
  26.     vector<vector<int>> adj;
  27.   public:
  28.     int res=0;
  29.     bool helper(int src, int par){
  30.         bool SELECT_ROOT=false;
  31.         for(auto nei: adj[src]){
  32.             if(nei!=par){
  33.                 bool isChildSelected=helper(nei,src);
  34.                 if(isChildSelected==false){
  35.                     SELECT_ROOT=true; // WE CANNOT BREAK OUT YET, WE NEED TO CHECK ALL CHILDREN BEFORE EXITING
  36.                 }
  37.             }
  38.         }
  39.         if(SELECT_ROOT==true){
  40.             res++;
  41.         }
  42.         return SELECT_ROOT;
  43.     }
  44.    
  45.     int countVertex(int N, vector<vector<int>>edges){
  46.         adj.resize(N+1);
  47.         res=0;
  48.         for(auto edge: edges){
  49.             adj[edge[0]].push_back(edge[1]);
  50.             adj[edge[1]].push_back(edge[0]);
  51.         }
  52.         helper(1,-1);
  53.         return res;
  54.     }
  55. };
  56.  
  57.  
Advertisement
Add Comment
Please, Sign In to add comment