fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int count(int A[],int num,int k){
  4. unordered_map<int,int>m;
  5. // m[0]=1;
  6. int count=0;
  7. int sum=0;
  8. int mini=1e9;
  9. for(int i=0;i<num;i++){
  10. sum+=A[i];
  11. int x=sum-k;
  12. m[0]=-1;
  13. if(m.find(x)!=m.end()){
  14. int dist=m[x]+1;
  15. int actual=i-dist+1;
  16. if(actual<mini){
  17. mini=actual;
  18. count=1;
  19. }
  20. else if(actual==mini){
  21. count++;
  22. }
  23.  
  24. }
  25. if(m.find(sum)==m.end()){
  26. m[sum]=i;
  27. }
  28.  
  29. }
  30. return count;
  31. }
  32.  
  33. int main() {
  34. // your code goes here
  35. int n;
  36. cin>>n;
  37. int k;
  38. cin>>k;
  39. int A[n];
  40. for(int i=0;i<n;i++){
  41. cin>>A[i];
  42. }
  43. cout<<"The count of subarrays with smallest length whose sum==k is:"<<count(A,n,k);
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 5276KB
stdin
8 15
10 5 2 7 1 9 8 7
stdout
The count of subarrays with smallest length whose sum==k is:2