RainX_69

Count Number of Substrings have count of 1s more than 0s | Hard | Segment Tree

Mar 5th, 2023
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | Source Code | 0 0
  1. https://practice.geeksforgeeks.org/problems/f72994353d123b925ff20f0694b662191df03ea2/1?page=1&difficulty[]=1&difficulty[]=2&status[]=unsolved&category[]=Dynamic%20Programming&category[]=Binary%20Search&category[]=Trie&category[]=union-find&sortBy=submissions
  2.  
  3. Given a binary string S consists only of 0s and 1s. The task is to calculate the number of substrings that have more 1s than 0s.
  4.  
  5. Example 1:
  6. Input:
  7. S = "011"
  8. Output: 4
  9. Explanation: There are 4 substring which
  10. has more 1s than 0s. i.e "011","1","11" and "1"
  11.  
  12. Example 2:
  13. Input:
  14. S = "0000"
  15. Output: 0
  16. Explanation: There is no substring
  17. which has more 1s than 0s
  18.  
  19. Constraints:
  20. 1 < |S| < 10^5
  21. |S| denotes the length of the string S
  22. ---------------------------------------------------------------------------------------------------------------------------------------
  23.  
  24.  
  25. class Solution{
  26. private:
  27.     vector<int> tree;
  28. public:
  29.   void update(int start, int end, int parent, long long index){
  30.       if(start>end){
  31.           return;
  32.       }
  33.       if(start==end){
  34.           tree[parent]++;
  35.           return;
  36.       }
  37.       int mid=(start+end)/2;
  38.       if(index>mid){
  39.           update(mid+1,end,2*parent+2,index);
  40.       }
  41.       else{
  42.           update(start,mid,2*parent+1,index);
  43.       }
  44.       tree[parent]=tree[2*parent+1]+tree[2*parent+2];
  45.   }
  46.  
  47.   int query(int start, int end, int parent, int qstart, int qend){
  48.       if(qstart>end || qend<start){
  49.           return 0;
  50.       }
  51.       if(qstart<=start && qend>=end){
  52.           return tree[parent];
  53.       }
  54.       int mid=(start+end)/2;
  55.       int L=query(start,mid,2*parent+1,qstart,qend);
  56.       int R=query(mid+1,end,2*parent+2,qstart,qend);
  57.       return L+R;
  58.   }
  59.  
  60.   long long countSubstring(string S){
  61.       int n=S.size();
  62.       tree.resize(4*2*n+1,0);
  63.      
  64.       int shift=n;
  65.       long long currSum=0;
  66.       long long res=0;
  67.      
  68.       update(0,2*n,0,0+shift);
  69.       for(int i=0;i<n;i++){
  70.           currSum+=(S[i]=='1' ? 1 : -1);
  71.          
  72.           /*    prefix[j]-prefix[i]>=1
  73.              or,prefix[i]<=1-prefix[j]
  74.           */
  75.           int lessThan=(currSum+shift)-1;
  76.           res+=query(0,2*n,0,0,lessThan);
  77.          
  78.           update(0,2*n,0,currSum+shift);
  79.       }
  80.       return res;
  81.   }
  82. };
Advertisement
Add Comment
Please, Sign In to add comment