ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

POJ-3061 (尺取法) -Subsequence

2019-08-02 11:40:15  阅读:228  来源: 互联网

标签:int 3061 Subsequence POJ 取法 端点 区间 include 枚举


题目:

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。若不存在,则输出0。

思路:此题可用尺取法去解决。

•在使用尺取法时应清楚以下四点:

• 1、 什么情况下能使用尺取法? 

•2、何时推进区间的端点?

•3、如何推进区间的端点?

·4、何时结束区间的枚举?

•一般用尺取法的时候判断以下三点: 

•  1. 尺取法所用的必须是连续的区间。

•   2. 尺取法所求的一般是通过对区间的调整来接近或达到某个条件

•   3. 尺取法的模型便是这样:根据区间的特征交替推进左右端点求解问题,其高效的原因在于避免了大量的无效枚举,其区间枚举都是根据区间特征有方向的枚举,如果胡乱使用尺取法的话会使得枚举量减少,因而很大可能会错误,所以关键的一步是进行问题的分析!

解题报告:1.先初始化区间的左右端点,

                   2.然后不断扩大右端点,直到符合条件,

                   3.然后在扩大左端点,直到条件不符合。回到第二部。

要注意何时区间枚举结束。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<vector>
#define Max 99999999
#define ll long long
using namespace std;
int t,n,s;
int a[100005],sum[100005];
int main()
{
	cin>>t;
	while(t--)
	{
		scanf("%d%d",&n,&s);
		int i,j,k;
		sum[0]=0;
		for(i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			sum[i]=sum[i-1]+a[i];//sum[i]代表前i项的和 
		}
		if(sum[n]<s)
		{
			printf("0\n");continue;//不存在 
		}
		int tail=1,head=1,ans=Max;
		while(tail<=head&&head<=n)//结束条件 
		{
			if(sum[head]-sum[tail-1]<s)
			{
				head++;continue;
			}
			while(sum[head]-sum[tail-1]>=s)
			{
				ans=min(ans,head-tail+1);//ans为符合条件的最短区间长度 
				tail++;
			}
		}
		printf("%d\n",ans);
	}
    return 0;
}

 

标签:int,3061,Subsequence,POJ,取法,端点,区间,include,枚举
来源: https://blog.csdn.net/weixin_44757834/article/details/98182567

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有