您的位置:首页 > 产品设计 > UI/UE

UVALive - 2678 Subsequence (尺取法)

2016-08-31 15:27 411 查看
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 nd the minimal length of the

subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to

S

.

Input

Many test cases will be given. For each test case the program has to read the numbers

N

and

S

,

separated by an interval, from the rst line. The numbers of the sequence are given in the second line

of the test case, separated by intervals. The input will nish with the end of le.

Output

For each the case the program has to print the result on separate line of the output le.

SampleInput

10 15

5 1 3 5 10 7 4 9 2 8

5 11

1 2 3 4 5

SampleOutput

2

3

题解:

这道题就是一个典型的尺取法。

好坑啊,如果序列全部加起来都没有s大,应该输出0。

#include<cstdio>
#include<cmath>
#include<iostream>
using namespace std;
#include<algorithm>

const int maxn=1e5+5;
long long a[maxn];

int main(){
int n;
long long s;
while(~scanf("%d%lld",&n,&s)){
for(int i=1;i<=n;++i){
scanf("%lld",&a[i]);
}
int slow=1,fast=1,ans=n;
long long sum=0;
while(true){
while(fast<=n && sum<s){
sum+=a[fast];
++fast;
}
if(sum>=s)
ans=min(ans,fast-slow);
sum-=a[slow];
++slow;
if(slow>n)break;
}
printf("%d\n",ans==n?0:ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: