Subsequence
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10875 | Accepted: 4493 |
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题解:让求连续的一个序列数之和大于等于S的最短序列长度;这道题,我前后换了三种方法才A了,刚开始看到,一想不就是个线段树,写完了发现答案不对。。。然后发现线段树只能找到一半,还呆加上区间合并,区间合并也很可能不对,然后想着树状数组,写了一半感觉还不如用个数组直接存到i的总值和,然后找到起点终点就好了,于是开始了暴力,暴力肯定超时啊;就想着二分下;调试了下就过了;二分还要判断下当前点与前一个点插哪个;可能我写的太麻烦了。。。有空看看大神怎么写的;AC代码:
#include<cstdio> #include<cstring> #include<cmath> #include<iostream> #include<algorithm> using namespace std; #define mem(x,y) memset(x,y,sizeof(x)) #define SI(x) scanf("%d",&x) #define PI(x) printf("%d",x) #define P_ printf(" ") #define ll root<<1 #define rr root<<1|1 #define lson ll,l,mid #define rson rr,mid+1,r const int INF=0x3f3f3f3f; const int MAXN=100010; int tree[MAXN]; int main(){ int T,N,M; SI(T); while(T--){ SI(N);SI(M); mem(tree,0); int ans=INF; int t=1; for(int i=0;i<N;i++){ int x; SI(x); if(!i)tree[i]=x; else tree[i]=tree[i-1]+x; } for(int i=N-1;i>=0;i--){ if(tree[i]-M>=0){ int t=lower_bound(tree,tree+i,tree[i]-M)-tree; if(tree[i]-tree[t]>=M)ans=min(ans,i-t); else ans=min(ans,i-t+1); //printf("%d\n",ans); } } if(ans==INF)puts("0"); else printf("%d\n",ans); } return 0; }