Subsequence(二分)

本文介绍了一个寻找最小子序列的问题,给定一系列正整数及目标值S,通过编程找到连续子序列的最小长度,该子序列的和大于等于S。使用C++实现,通过二分查找优化解题过程。

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

一开始c++交不过,g++过,原来是int 输入的时候是long long,wa了,g++交没这个问题

代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<cmath>

const int maxn=1e5+5;
typedef long long ll;
using namespace std;
ll a[maxn];
ll s[maxn];
ll n,ss;
bool check(int x)
{
    if(x>=n)
    {
    	return true;
	}
	for(int t=x;t<=n;t++)
	{
//		cout<<s[t]<<" "<<s[t-x+1]<<endl;
		if(s[t]-s[t-x+1]>=ss)
		{
			
			return true;
		}
	}
	return false;
}
int  main()
{
	int  T;
	cin>>T;
	while(T--)
	{
		scanf("%lld%lld",&n,&ss);
		for(int t=1;t<=n;t++)
		{
			scanf("%lld",&a[t]);
		}
		memset(s,0,sizeof(s));
		for(int t=1;t<=n;t++)
		{
			s[t]=s[t-1]+a[t];
		}
		if(s[n]<ss)
		{
			cout<<"0"<<endl;
	    }
	    else
	    {
		int l=0,r=100000;
		int mid;
		while(l<=r)
		{
			mid=(l+r)/2;
			if(check(mid))
			{
		      r=mid-1;
			}
			else
			{
			  l=mid+1;
			}
		}
		mid=(l+r)/2;
		cout<<mid<<endl;
	   }
	}
	
	return 0;
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

black-hole6

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值