A - Subsequence
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
Submit
Status
Practice
POJ 3061
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的最小长度,没有输出0;
- 思路:设两个指针分别代表满足要求的区间的左边和右边,当不满足时右区间移动,使序列变长,满足要求时,左区间向右移动使区间变短,指导R>N时结束,在此过程中应不断更新答案;
- 失误:尺取知道什么意思就是写不出来,还是找一组数据一步步模拟,一步步写。
- 代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100000+33];
int ans,S,N;
void solve()
{
ans=100000+44;
int L=1,R=1,sum=0,lsub=0;
while(R<=N)
{
while(sum<S&&R<=N)//R总指向当前满足要求区间的下一个 注意此处R可能>N
{
sum+=a[R]; ++R; ++lsub;
}
while(sum>=S)//L总指向当前区间的最左边 左闭右开
{
sum-=a[L]; ++L; --lsub;
}
ans=min(ans,lsub+1);
}
}
int main()
{
int T,i,sum;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&N,&S);
sum=0; bool flag=false;
for(i=1;i<=N;++i)
{
scanf("%d",&a[i]);
sum+=a[i];
if(sum>=S&&!flag) flag=true;
}
if(!flag)
{
printf("0\n"); continue;
}
solve();
printf("%d\n",ans);
}
return 0;
}