【POJ 3061】Subsequence(二分法)

来源:互联网 发布:php 访问私有属性 编辑:程序博客网 时间:2024/06/05 04:31



点击打开题目


Subsequence
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 15811 Accepted: 6672

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

210 155 1 3 5 10 7 4 9 2 85 111 2 3 4 5

Sample Output

23

Source

Southeastern Europe 2006

题意:找最短的连续元素的级大于s,输出元素个数。

题解:前缀二分法基础题,这里用是 stl 的 lower_pound 函数

代码:


#include<iostream>#include<algorithm>#include<cstring>using namespace std;int a[100100];int main(){int T;cin>>T;while(T--){int n,s;cin>>n>>s;for(int i=0;i<n;i++){cin>>a[i];a[i]=a[i-1]+a[i];}if(a[n-1]<s)cout<<"0"<<endl;else{int ans=n;for(int i=0;a[i]+s<=a[n-1];i++){int d=lower_bound(a+i,a+n,a[i]+s)-a;ans=min(ans,d-i);}cout<<ans<<endl;} }return 0;}

错误代码:没有二分,查找时间慢,查找不完全

#include<iostream>#include<algorithm>#include<cstring>using namespace std;int a[100500]; bool cmp(int a,int b){return a>b;}int main(){int T;cin>>T;while(T--){memset(a,0,sizeof(a));int n,s;cin>>n>>s;for(int i=0;i<n;i++)cin>>a[i];sort(a,a+n,cmp);//n=unique(a,a+n)-a;int ans=a[0];int flag=1;for(int i=1;i<n;i++){if(ans>=s){cout<<i<<endl;flag=0;break;}ans+=a[i];} if(flag)cout<<"0"<<endl;}return 0;}