题目
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
自写
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int N=1e5;
int li[N];
int out[N];
int main(){
out[1]=0;
int a;
cin>>a;
while(a--){
int n,s;
int j=1;
cin>>n;
cin>>s;
for(int i=1;i<=n;i++){
cin>>li[i];
}
int sum=0;
int l=1;
int r=1;
int res=n+1;
while(r<=n){
if(sum>=s){
res=min(res,r-l);
sum-=li[l];
l++;
}
if(sum<s){
sum+=li[r];
r++;
}
}
if(res>n)res=0;
cout<<res<<endl;
}
return 0;
}
结合网上的
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int N=100005;
int li[N];
int main(){
int a;
cin>>a;
while(a--){
int n,s;
cin>>n;
cin>>s;
for(int i=1;i<=n;i++){
cin>>li[i];
}
int sum=0;
int l=1;
int r=1;
int res=n+1;
while(true){
while(r<=n&&sum<s){
sum+=li[r];
r++;//注意r++应在累加之后防止在边界时溢出
}
if(sum<s)break;
res=min(res,r-l); //???
sum-=li[l];
l++;
}
if(res>n)res=0;//注意判断没有的情况
cout<<res<<endl;
}
return 0;
}
网上的
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int a[100005];
int n,S;
void slove()
{
int res=n+1;
int s=0,sum=0,z=0;
for(;;)
{
while(z<n&&sum<S)
{
sum+=a[z++];
}
if(sum<S)break;
res=min(res,z-s);
sum-=a[s++];
}
if(res>n)
res=0;
cout<<res<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>S;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
slove();
}
}