POJ - 3061 尺取

尺取

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
he 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个正整数(10<n<100 000)的序列,每个正整数小于或等于10000,以及一个正整数s(s<100 000 000)。编写一个程序,找出序列中 连续 元素子序列的最小长度,其和大于或等于s

于先在连续的一个范围内寻找符合条件的一个区间和,因此考虑用尺取**(一般都是root在后(左),j在前(右),就像尺子一样,这段不行就继续伸缩,一般都是j先括,符合条件了,就缩root,不符合条件就括j,每次找到符合的时候,更新自己所要找的答案) **

因此代码如下:

#include<stdio.h>
int a[100005];
long s;
int main()
{ 	int n,i,root,j,sum,min,T;
	 scanf("%d",&T);			//输入样例个数
	 while(T--)
	 { 	scanf("%d %ld",&n,&s);		//n个整数,s为题目的总和
	 	sum=j=root=0;
	  	min=n+1;		//min记录sum>=s的最小长度,刚开始初始化为最长
	 	 for(i=0;i<n;i++)
	  		 scanf("%d",&a[i]); 	//输入
	 	 for(;;)
	 	 { 
	 	 	while(j<n&&sum<s)  	//如果 j 小于n,而且sum小于s(不符合题目条件)
	  		 	sum+=a[j++];	 //跳出循环即此时的sum>=s或者 j已经超出n而sum仍然小于s
	   		if(sum<s)  break;  	//即使全部加起来也不满足题意,没有符合的最短序列
	   		min=min>j-root?j-root:min;	//更新符合条件的序列长度
	  		 sum-=a[root++];		//现在符合题意了,就缩root
	  	}
		  if(min>n)min=0;	
		  printf("%d\n",min);
	 }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值