Advertisement
tepyotin2

Subarray Sum II

Jun 20th, 2025
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.55 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6.  
  7. int n;
  8. ll x;
  9. vector<ll> arr;
  10. ll ans;
  11.  
  12. int main(){
  13.     //freopen("subsumsII.in", "r", stdin);
  14.    
  15.     cin >> n >> x;
  16.     arr.resize(n+1);
  17.     for(int i=0; i<n; i++){
  18.         cin >> arr[i];
  19.     }
  20.     ll sum = 0;
  21.     //unordered_map<ll, int> freq;
  22.     map<ll, int> freq;
  23.     //map better performance
  24.     //unordered map result in time limit exceeded
  25.     freq[0] = 1;
  26.     for(int i=0; i<n; i++){
  27.         sum+=arr[i];
  28.         ll val = sum-x;
  29.         ans+=freq[val];
  30.         freq[sum]++;
  31.     }
  32.     cout << ans << '\n';
  33.    
  34.     return 0;
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement