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<algorithm>
#include<cmath>
#define ll long long
using namespace std;
const int maxx=1e5+100;
int a[maxx];
int n,m;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
int l=1,r=1;
int ans=0;
int sum=1e9+1;
while(r<=n)
{
while(ans<m&&r<=n) ans+=a[r],r++;
while(ans>=m) ans-=a[l],l++;
if(r<=n)sum=min(sum,r-l+1);
}
printf("%d\n",sum==1e9+1?0:sum);
}
return 0;
}
二分代码:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int n,s;
int a[100010];
int ans;
int ko(int m)
{
if(s==0) return 1;
int temp=0;
for(int i=1;i<=n-(m-1);i++)
{
temp=a[i+(m-1)]-a[i-1];
if(s<=temp) return 1;
}
return 0;
}
void sde()
{
ans=0;
int l=1,r=n;
int m=(l+r)/2;
while(l<r)
{
if(ko(m)) r=m;
else l=m+1;
m=(l+r)/2;
}
ans=m;
}
void input()
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
a[i]=a[i-1]+a[i];
}
}
int main()
{
int k;
cin>>k;
while(k--)
{
cin>>n>>s;
input();
sde();
if(ans!=n)
cout<<ans<<endl;
else if(a[n]<s)
{
cout<<0<<endl;
}
else cout<<n<<endl;
}
return 0;
}
努力加油a啊,(o)/~