【POJ】3061---Subsequence(二分)

                                   SubsequencePOJ - 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
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

 

思路分析:
            (1):题意:找到一个连续子串,该子串所有数据之和大于等于k,并且使该子串长度最小。
            (2):思路:涉及到几个数据之和,就会很自然地想到前缀和哦,用数组s[i]表示前缀和,下标从1开始存,即s[0]=0,s[1]=a[1],s[2]=s[1]+a[2], .....;
                               如果s[n]<k,说明所有数据的和就小于k,那么肯定不符合条件,直接输出0,continue;
                               数组a[i]不一定按照递增顺序,但是都是正整数,所以数组s[i]一定是递增的,是按照一定顺序排列的,所以对于s[i]可以使用二分查找的思路。
            (3):二分关键:关键步骤是lower_bound(s+1,s+n+1,s[i]+k)-s;区间左端点是s[1],右端点是s[n],所以[s+1,s+n+1)前闭后开的区间,返回值ans是
                                       第一个大于等于s[i]+k的位置(因为要使子串长度最小,所以每次循环找到第一个符合条件的就是当前循环的最小,然后每次循环比较找
                                      到最小),说明ans所在位置的s[j]的值减去s[i] 得到的差大于等于k,从s[i]加到s[j]一共加了ans-1个数据,所以子串长度为ans-1;i从1
                                      到n循环,找到最小的ans-1.


代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100000+11],s[100000+11];
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		memset(s,0,sizeof(s));
		int n,k;
		scanf("%d%d",&n,&k);
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			s[i]=s[i-1]+a[i];						//前缀和 
		}
		if(s[n]<k)		//所有和加起来还小于k,肯定不行,直接输出0 
		{
			printf("0\n");
			continue;
		}
		int ans;
		ans=lower_bound(s+1,s+n+1,s[1]+k)-s;//s数组由于是叠加起来的,所以按照从小到大的顺序排列,找到第一个大于等于s[1]+k的位置下标 
		int l=ans-1;
		for(int i=2;i<=n;i++)
		{
			if(s[n]-s[i]<k)
				break;
			ans=lower_bound(s+1,s+n+1,s[i]+k)-s; 
			if(ans-i<l)
				l=ans-i;
		}
		printf("%d\n",l);
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值