题目描述
You are given a sequence of positive integers of length N, A=a1,a2,…,aN, and an integer K. How many contiguous subsequences of A satisfy the following condition?
·(Condition) The sum of the elements in the contiguous subsequence is at least K.
We consider two contiguous subsequences different if they derive from different positions in A, even if they are the same in content.
Note that the answer may not fit into a 32-bit integer type.
Constraints
·1≤ai≤105
·1≤N≤105
·1≤K≤1010
输入
Input is given from Standard Input in the following format:
N K
a1 a2 … aN
输出
Print the number of contiguous subsequences of A that satisfy the condition.
样例输入 Copy
【样例1】
4 10
6 1 2 7
【样例2】
3 5
3 3 3
【样例3】
10 53462
103 35322 232 342 21099 90000 18843 9010 35221 19352
样例输出 Copy
【样例1】
2
【样例2】
3
【样例3】
36
提示
样例1解释
The following two contiguous subsequences satisfy the condition:
·A[1…4]=a1,a2,a3,a4, with the sum of 16
·A[2…4]=a2,a3,a4, with the sum of 10
样例2解释
Note again that we consider two contiguous subsequences different if they derive from different positions, even if they are the same in content.
题意:
给你n个数和一个k,问你有多少个连续的子序列之和>=k。
解析:
求一个前缀和。前缀和肯定是一个单调递增的。
通过公式得出sum[x]>=sum[y-1]+k
所以我们只要二分出第一个>=的,那么后面都会满足(n-t+1)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e6+100;
ll sum[N];
ll a[N];
int n;
ll k;
ll find(int l,int r,ll x)
{
int ans=-1;
while(l<=r)
{
int mid=l+r>>1;
if(x<=sum[mid]) r=mid-1,ans=mid;
else l=mid+1;
}
return ans;
}
int main()
{
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++) sum[i]=sum[i-1]+a[i];
ll ans=0;
for(int i=1;i<=n;i++)
{
int t=find(i,n,k+sum[i-1]);
// cout<<t<<endl;
if(t==-1) break;
ans+=(n-t+1);
}
cout<<ans<<endl;
}