RainX_69

Find count of good stones (Dynamic Programming) (graph cycles) HARD

Feb 16th, 2023
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.21 KB | Source Code | 0 0
  1. https://practice.geeksforgeeks.org/problems/e2d156755ca4e0a9b9abf5680191d4b06e52b1a8/1
  2.  
  3. Geek is in a geekland which have a river and some stones in it. Initially geek can step on any stone. Each stone has a number on it representing the value of exact step geek can move. If the number is +ve then geeks will move right by arr[i] and if the number is -ve then geeks move left by arr[i]. Bad Stones are defined as the stones in which if geeks steps, will reach a never ending loop whereas good stones are the stones which are safe from never ending loops. Return the number of good stones in river.
  4.  
  5. Example 1:
  6.  
  7. Input: [2, 3, -1, 2, -2, 4, 1]
  8. Output: 3
  9. Explanation: Index 3, 5 and 6 are safe only. As index 1, 4, 2 forms a cycle and from index 0 you can go to index 2 which is part of cycle.
  10.  
  11. Example 2:
  12.  
  13. Input: [1, 0, -3, 0, -5, 0]
  14. Output: 2
  15. Explanation: Index 2 and 4 are safe only. As index 0, 1, 3, 5 form cycle.
  16.  
  17. Expected Time Complexity : O(N), N is the number of stones
  18. Expected Auxiliary Space : O(N), N is the number of stones
  19.  
  20. Constraints:
  21.    1 <= n < 10^5 (where n is the length of the array)
  22.   -1000 <= arr[i] < 1000
  23. ------------------------------------------------------------------------------------------------------------------------------------
  24.  
  25. class Solution{
  26. public:
  27.     bool isBad(vector<int> &arr, int curr, vector<string> &states){
  28.         if(curr>=arr.size() || curr<0 || states[curr]=="GOOD"){
  29.             return false;  // not bad
  30.         }
  31.         if(states[curr]=="PROCESSING" || states[curr]=="BAD"){
  32.             return true; // bad
  33.         }
  34.         states[curr]="PROCESSING"; // NODE UNDER PROCESS
  35.         bool answer=isBad(arr,curr+arr[curr],states);
  36.         if(answer==true){
  37.             states[curr]="BAD";
  38.         }
  39.         else{
  40.             states[curr]="GOOD";
  41.         }
  42.         return answer;
  43.     }
  44.    
  45.     int goodStones(int n,vector<int> &arr){
  46.         vector<string> states(n,"NULL");
  47.         for(int i=0;i<n;i++){
  48.             if(states[i]=="NULL"){
  49.                 isBad(arr,i,states);
  50.             }
  51.         }
  52.         int res=0;
  53.         for(auto c: states){
  54.             if(c=="GOOD"){
  55.                 res++;
  56.             }
  57.         }
  58.         return res;
  59.     }  
  60. };
Advertisement
Add Comment
Please, Sign In to add comment