RainX_69

Count substrings with K 1's (CODEFORCES IMPORTANT)

Jan 21st, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | Source Code | 0 0
  1. https://codeforces.com/problemset/problem/165/C
  2.  
  3. A string is binary, if it consists only of characters "0" and "1".
  4. String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
  5. You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
  6.  
  7. Examples
  8.  
  9. input
  10. 1
  11. 1010
  12. output
  13. 6
  14.  
  15. input
  16. 2
  17. 01010
  18. output
  19. 4
  20.  
  21. input
  22. 100
  23. 01010
  24. output
  25. 0
  26.  
  27. Note
  28. In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
  29. In the second sample the sought substrings are: "101", "0101", "1010", "01010".
  30.  
  31. ----------------------------------------------------------------------------------------------------------------------
  32. #include<bits/stdc++.h>
  33. using namespace std;
  34.  
  35. void solve(){
  36.    int k;
  37.    cin>>k;
  38.    string s;
  39.    cin>>s;
  40.    long long int sum=0;
  41.    long long int res=0;
  42.    unordered_map<long long int,long long int> mpp;
  43.    for(auto x: s){
  44.       sum+=(x=='1' ? 1 : 0);
  45.       if(sum==k){
  46.          res++;
  47.       }
  48.       if(mpp.find(sum-k)!=mpp.end()){
  49.          res+=mpp[sum-k];
  50.       }
  51.       mpp[sum]++;
  52.    }
  53.    cout<<res;
  54. }
  55. int main(){
  56.    int TC=1;
  57.    while(TC--){
  58.       solve();
  59.    }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment