A

来源:互联网 发布:知乎怎么用 编辑:程序博客网 时间:2024/05/18 01:23

、点击打开链接

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

题解:满足条件的最短连续子序列元素个数;



今天说是练习二分法,可是我自己用其他的方法也能解决




#include<cstdio>#include<iostream>#include<algorithm>using namespace std;const int maxn=100009;int a[maxn];int n,s;int main(){int t;while(scanf("%d",&t)!=EOF){for(int i=0;i<t;i++){scanf("%d%d",&n,&s);for(int j=1;j<=n;j++){scanf("%d",&a[j]);}int w=1,e=1,sum=0,ans=n+1;for(;;){while(e<=n&&sum<s){sum+=a[e++];}if(sum<s) break;ans=min(ans,e-w);sum-=a[w++];}if(ans==n+1)  printf("0\n");else printf("%d\n",ans);}}return 0;}








原创粉丝点击