Subsequence
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 21165 | Accepted: 9046 |
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
以下参考自《挑战程序设计竞赛(第二版)》
O(nlogn)解法:
先利用前缀和的思想预处理,以O(n)的时间计算好sum[i](sum[i]=a[1]+a[2]+……+a[i]),就可以以O(1)的时间计算区间上的总和。这样一来,子序列的起点s确定以后,便可以用二分搜索法快速地确定使序列和不小于S的结尾t的最小值。
AC代码:
#include<iostream>
#include<sstream>
#include<algorithm>
#include<string>
#include<iomanip>
#include<vector>
#include<cmath>
#include<ctime>
#include<stack>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int N,S,a[100010],sum[100010]={0};
cin>>N>>S;
for(int i=1;i<=N;i++)
{
cin>>a[i];
sum[i]=sum[i-1]+a[i];//预处理,sum[i]为a[1]到a[i]的和
}
if(sum[N]<S) //解不存在
{
cout<<'0'<<endl;continue;
}
int res=N;
for(int s=1;sum[s]+S<=sum[N];s++)//枚举起点的位置
{
int t=lower_bound(sum+s+1,sum+N+1,sum[s]+S)-sum;//序列和不小于S的结尾t的最小值
res=min(res,t-s); //序列长度的最小值
}
cout<<res<<endl;
}
}
-----------------------------------------------------------------------
2020-4-7更新
上述代码有bug,惭愧惭愧,详见评论区
-----------------------------------------------------------------------
O(n)解法
设以开始总和最初大于S时的连续子序列为,这时,所以从开始总和最初超过S的连续子序列如果是的话,则必然有。利用这一性质便可以设计出如下算法:
(1)以s=t=sum=0初始化。
(2)只要依然有sum<S,就不断将sum增加,并将t增加1。
(3)如果(2)中无法满足sum>=S则终止。否则的话,更新res=min(res,t-s)。
(4)将sum减去,s增加1然后回到(2)。
对于这个算法,因为t最多变化n次,因此只需要O(n)的复杂度就可以求解这个问题了。像这样反复地推进区间的开头和末尾,来求取满足条件的最小区间的方法被称为尺取法。
AC代码:
#include<iostream>
#include<sstream>
#include<algorithm>
#include<string>
#include<iomanip>
#include<vector>
#include<cmath>
#include<ctime>
#include<stack>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int N,S,a[100010];
cin>>N>>S;
for(int i=1;i<=N;i++) cin>>a[i];
int res=N+1,s=1,t=1,sum=0;
for(;;)
{
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;
}
}