题目:
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
题目大意:给出了n个正整数序列,求该序列中连续子序列的最小长度,且子序列的和大于等于s。若不存在,则输出0。
思路:此题可用尺取法去解决。
•在使用尺取法时应清楚以下四点:
• 1、 什么情况下能使用尺取法?
•2、何时推进区间的端点?
•3、如何推进区间的端点?
·4、何时结束区间的枚举?
•一般用尺取法的时候判断以下三点:
• 1. 尺取法所用的必须是连续的区间。
• 2. 尺取法所求的一般是通过对区间的调整来接近或达到某个条件
• 3. 尺取法的模型便是这样:根据区间的特征交替推进左右端点求解问题,其高效的原因在于避免了大量的无效枚举,其区间枚举都是根据区间特征有方向的枚举,如果胡乱使用尺取法的话会使得枚举量减少,因而很大可能会错误,所以关键的一步是进行问题的分析!
解题报告:1.先初始化区间的左右端点,
2.然后不断扩大右端点,直到符合条件,
3.然后在扩大左端点,直到条件不符合。回到第二部。
要注意何时区间枚举结束。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<vector>
#define Max 99999999
#define ll long long
using namespace std;
int t,n,s;
int a[100005],sum[100005];
int main()
{
cin>>t;
while(t--)
{
scanf("%d%d",&n,&s);
int i,j,k;
sum[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];//sum[i]代表前i项的和
}
if(sum[n]<s)
{
printf("0\n");continue;//不存在
}
int tail=1,head=1,ans=Max;
while(tail<=head&&head<=n)//结束条件
{
if(sum[head]-sum[tail-1]<s)
{
head++;continue;
}
while(sum[head]-sum[tail-1]>=s)
{
ans=min(ans,head-tail+1);//ans为符合条件的最短区间长度
tail++;
}
}
printf("%d\n",ans);
}
return 0;
}