Poj 3061 尺取法模板题:【题解】

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

题目大意

给你N个正整数,和一个S,S < 1e8, 按照顺序找到一个序列的和大于等于S,想办法让序列里数字个数最少。本题要用到尺取法,尺取法通常是对数组保存一对下标,即所选取的区间的左右端点,然后根据实际情况不断地推进区间左右端点以得出答案。即不断移动左右端点。题目控制条件:右端点小于等于N,当sum < S 时,先让右端点移动,如果存在一个区间大于等于S了,就可以暂时停止移动右端点,让左端点向右移动,减小sum值,找到最小的sum 且 sum >= S ,每次用min取序列的最小长度。
本题中还用到了INF 0x3f3f3f3f ,一个最大值量。
如果我们想对数组清零,会用到memset(a, 0, sizeof(a)),方便又高效。那么,当我们想对数组设置为无穷大时,可以将无穷大设置为0x3f3f3f3f,然而,0x3f3f3f3f的每个字节都是0x3f!所以只需要memset(a, 0x3f, sizeof(a))。

AC代码如下:

#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#define MAX 100005  
#define LL long long  
#define INF 0x3f3f3f3f  
using namespace std;  
LL a[100010];
int n, t, ans = INF;
LL sum, s;
int main(){
	scanf("%d",&t);
	while(t--){
		scanf("%d %I64d", &n, &s);
		for(int i = 0; i < n; i ++)
			scanf("%I64d", a+i);
		int start = 0, end = 0;
		ans = INF; sum = 0;
		while(1){
			while(end < n && sum <s)
				sum += a[end++];
			if(sum < s)  break;
			ans = min(ans, end - start);
            sum -= a[start++];
		}
		if(ans == INF)  ans = 0;
		printf("%d\n", ans);
	}
    return 0;
}

#其实下边这个板子更好理解:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
ll a[100005], S;
int main(){
	int t, N;
	while(scanf("%d", &t) != EOF){
		while(t--){
			scanf("%d %I64d", &N, &S);
			for(int i = 1; i <= N; i ++){
				scanf("%I64d", &a[i]);
			}
			int l = 1, r = 1;
			ll sum = 0;
			int minn = INF;
			while(r <= N){
				sum += a[r];		 
				r ++;				// r后移 
				while(sum >= S){
					minn = min(minn, r - l);
					sum -= a[l];
					l ++;
				}
			}
			if(minn == INF)	cout << "0" << endl;
			else	printf("%d\n", minn);
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值