Subarray Sums II
题目描述
Given an array of n integers, your task is to count the number of subarrays having sum x.
输入
The first input line has two integers n and x: the size of the array and the target sum x.
The next line has n integers a1,a2,...,an: the contents of the array.
Constraints
1 ≤ n ≤
≤ x,ai ≤
输出
Print one integer: the required number of subarrays.
样例输入
5 7
2 -1 3 5 -2
样例输出
2
思路分析
利用前缀和 k=prefix[i]-prefix[j](j<i),加哈希表。
初始哈希表mp[0]=1。
在输入数组x的过程中:先计算出前缀和prefix[i](prefix[i]=x[1]+...+x[i]);然后查找j(j<i)满足k=prefix[i]-prefix[j],也就是prefix[j]=prefix[i]-k,更新和为k的子数组数量ans为ans+mp[prefix[j]];最后将prefix[i]存入哈希表。
代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,k,x;
ll ans,prefix;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>n>>k;map<ll,int>mp;mp[0]=1;for(int i=1;i<=n;i++){cin>>x;prefix+=x;ans+=mp[prefix-k];mp[prefix]++;}cout<<ans;return 0;
}