- 题意:给定长度为n的数列整数a0,a2,…an-1以及整数S。求出总和不小于S的连续子序列的长度的最小值。如果解不存在,则输出0。
- problem link:http://poj.org/problem?id=3061
- 尺取法通常是指保存数组的一对下标(起点和终点)。然后不断推进两个端点最终得到答案的方法。
- AC code:
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e5+6;
int n,a[N],S;
int main(){
ios::sync_with_stdio(false);cin.tie(0);
int T;cin>>T;
while(T--){
cin>>n>>S;
for(int i=0;i<n;i++)cin>>a[i];
int t=0,sum=0,s=0,res=n+1;
while(1){
while(t<n&&sum<S)sum+=a[t++];
if(sum<S)break;
res=min(res,t-s);
sum-=a[s++];
}
if(res>n)res=0;
cout<<res<<endl;
}
}
- 此题的样例一数据:
输入:
10 15
5 1 3 5 10 7 4 9 2 8
端点(起点和终点)推进过程图示:
