题目链接:http://poj.org/problem?id=3061
Subsequence
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7752 | Accepted: 2962 |
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
Source
照着挑战程序设计竞赛书做的一道,题目大意:给定长度为n的数列整数a0,a1,…,an以及整数S。求出总和不小于S的连续子序列的长度的最小值。如果解不存在,则输出0。
思路一:二分,开始O(n)处理出数列的前缀和,然后枚举子序列开始位置,二分求出子序列长度,总复杂度O(nlogn)
代码如下:
/**
* @author neko01
*/
//#pragma comment(linker, "/STACK:102400000,102400000")
#include <cstdio>
#include <cstring>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
typedef long long LL;
#define INF 0x7fffffff
const double pi=acos(-1.0);
const double eqs=1e-10;
int a[100005];
int sum[100005];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
sum[0]=0;
int n,S;
scanf("%d%d",&n,&S);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
}
int ans=n;
if(sum[n]<S)
{
printf("0\n");
continue;
}
for(int i=1;sum[i]+S<=sum[n];i++)
{
int x=lower_bound(sum+i,sum+n+1,sum[i]+S)-(sum+i);
ans=min(x,ans);
}
printf("%d\n",ans);
}
return 0;
}
思路二,尺取法(追逐法)
直接贴书上的吧:
(1) 以s= t= sum = 0初始化。
(2) 只要依然有sum<S,就不断将sum增加at,并将t增加1。
(3) 如果(2)中无法满足sum≥S则终止。否则的话,更新res = min(res, t-s)。
(4) 将sum减去as,s增加1然后回到(2)。
这样其实把每个总和恰好大于等于S的子序列都找到了,所以结果肯定是正确的,而且他t最多变化n次,复杂度O(n).
代码如下:
/**
* @author neko01
*/
//#pragma comment(linker, "/STACK:102400000,102400000")
#include <cstdio>
#include <cstring>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
typedef long long LL;
#define INF 0x7fffffff
const double pi=acos(-1.0);
const double eqs=1e-10;
int a[100005];
int main()
{
int T;
scanf("%d",&T);
int n,S;
while(T--)
{
scanf("%d%d",&n,&S);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
int s=1,t=1,sum=0,ans=n+1;
while(1)
{
while(t<=n&&sum<S)
{
sum+=a[t++];
}
if(sum<S)
break;
if(t-s<ans)
ans=t-s;
sum-=a[s++];
}
if(ans>n)
printf("0\n");
else
printf("%d\n",ans);
}
return 0;
}