poj 3061 (尺取法)

给定一个包含正整数的序列和一个正整数目标S,找出序列中连续元素子序列的最小长度,使得子序列之和大于或等于S。若不存在这样的子序列,则输出0。解决方案涉及到前缀和和区间最小长度的搜索。
摘要由CSDN通过智能技术生成

Subsequence

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 24441 Accepted: 10320

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

题意:给定一个序列,找出最短的子序列长度,使得其和大于或等于S。


分析:首先,序列都是正数,如果一个区间其和大于等于S了,那么不需要在向后推进右端点了,因为其和也肯定大于等于S但长度更长,所以,当区间和小于S时右端点向右移动,和大于等于S时,左端点向右移动以进一步找到最短的区间,如果右端点移动到区间末尾其和还不大于等于S,

结束区间的枚举。

这个题目区间和明显是有趋势的:单调变化,所以根据题目要求很容易求解,但是在使用之间需要对区间前缀和进行预处理计算。
 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<string>

using namespace std;
const int N=1e5+10;
const int inf=0x3f3f3f3f;
typedef long long LL;
LL s[N];
int main()
{
	int T;
	scanf("%d",&T);
	while(T--){
		int n;
		LL num;
		scanf("%d %lld",&n,&num);
		int st=0,en=0;
		for(int i=0;i<n;i++) scanf("%lld",&s[i]);
		LL sum=0;
		int ans=inf;
		while(true){
			//cout<<"****"<<sum<<endl;
			while(en<n&&sum<num){
				sum+=s[en++];
			}
			if(sum<num) break;
			ans=min(ans,en-st);
			sum-=s[st++];
		}
		printf("%d\n",ans==inf?0:ans);
	}
	return 0;
 } 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值