问题 J: Enough Array------------------思维+前缀和+二分

题目描述
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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值