Unacknowledged scientist Victor conducts a pseudoscientific research of the relation between integers that cross his mind and the integer that comes into his assistant's mind. He wrote the integers a1, ..., an which had crossed his mind. Then it turned up that the integer s had come into his assistant's mind. Victor wants to determine how many consecutive non-empty sets of integers al, al + 1, ..., ar (l ≤ r) have the sum al + al + 1 + ... + ar = s.
The first line contains two integers separated by space: n and s (1 ≤ n ≤ 200000, - 2·1014 ≤ s ≤ 2·1014) — the number of integers which crossed Victor's mind and the integer that came into his assistant's mind.
The second line contains n integers separated by space: ai ( - 109 ≤ ai ≤ 109) — the integers which crossed Victor's mind.
Output the only integer — the number of consecutive non-empty sets of integers which have the sum s.
5 2 -1 1 2 -1 1
5
6 3 3 -2 1 -1 1 2
3
解析
给一串数,求区间和为k的子区间个数
动态规划的思想。首先求一个前缀和,当Prefix_Sum[R] - Prefix_Sum[L] = K时,区间(L,R]为满足条件的区间。
等式变形Prefix_Sum[L] = Prefix_Sum[R] - K 。那么R以前,前缀和恰为Prefix_Sum[R] - K的Prefix_Sum[L]就可以和R凑成一个合法的区间。
也就说记录R前Prefix_Sum[L]出现的次数就可以了。
#include<cstdio>
#include<map>
using namespace std;
typedef long long LL;
LL Prefix_Sum[200100];
map<LL,LL> Map;
LL N,K;
int main()
{
scanf("%I64d%I64d",&N,&K);
for(int i=1;i<=N;i++)
{
scanf("%I64d",&Prefix_Sum[i]);
Prefix_Sum[i]+=Prefix_Sum[i-1];
}
LL ans=0; Map[0]=1;
for(int i=1;i<=N;i++)//(L,R]
{
ans+=Map[(Prefix_Sum[i]-K)];
Map[Prefix_Sum[i]]++;
}
printf("%I64d",ans);
return 0;
}