Poj 3061 Subsequence(二分+前缀和)
Subsequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12333 Accepted: 5178
Description
A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.
Input
The first line is the number of test cases. For each test case the program has to read the numbers N and S, separated by an interval, from the first line. The numbers of the sequence are given in the second line of the test case, separated by intervals. The input will finish with the end of file.
Output
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
Sample Input
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
Sample Output
2
3
Source
Southeastern Europe 2006
/*
题目大意:
要求n个数总和不小于s的连续子序列的长度的最小值.
二分+前缀和查询.
*/
#include<iostream>
#include<cstdio>
#define MAXN 100001
using namespace std;
int n,m,s[MAXN],sum[MAXN];
bool check(int x)
{
for(int i=1;i<=n-x+1;i++){
if(sum[x+i-1]-sum[i-1]>=m) return true;
}
return false;
}
int erfen(int l,int r)
{
int mid,ans=0;
while(l<=r){
int mid=(l+r)>>1;
if(check(mid)) ans=mid,r=mid-1;
else l=mid+1;
}
return ans;
}
int main()
{
int t;scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&s[i]),sum[i]=s[i]+sum[i-1];
printf("%d\n",erfen(0,n+1));
}
return 0;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步