牛客 1.17 Subsequence(尺取法,二分)

第17节 Subsequence
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.

输入描述:

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.

输出描述:

For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
示例1
输入
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
输出
2
3


求出总和不小于S的连续子序列的长度的最小值。

尺取法思路:
首先要找到从第一个数为开端,满足条件的序列,即找到从 a[1] 开始到 a[end] 的序列,如果能找到,则一定存在一个len,否则,就不存在满足条件的序列。

找到这个序列后,begin 右移,再找end, end只能往右边找,如果能找到这样的end,更新len的最小值,begin再右移,依次循环(相当于begin从1到n扫一遍,复杂度O(n),), 当找不到end时,跳出循环。

最后如果len值还是初始化的值,表示没有找到一个符合条件的end,即找不到符合条件的子序列,否则输出len

//#include <bits/stdc++.h>
#include <iostream>

using namespace std;
typedef long long ll;
const int N=1e5+5;
ll a[N];

int solve(int n,int s) {

	for(int i=1; i<=n; i++) {
		cin>>a[i];		
	}
	int begin=0,end=0,len=n+1;
	ll sum=0;
	//int sum=0;
	while(1)
	{
		while(end<n&&sum<s)//在从begin后一个数为开头,找一个序列和大于等于s的片段 
		{
			end++;
			sum+=a[end];			
		}
		if(sum<s) break;//此时end=n ,跳出循环
		//更新最短长度 
		len=min(len,end-begin) ;//序列包括end,不包括begin
		//片段左端右移一个数 
		begin++;
		sum-=a[begin]; 
	}
	return len>n?0:len;
}

int main() {
	int t;
	cin>>t;
	while(t--) {
		int n,s;
		cin>>n>>s;
		cout<<solve(n,s)<<endl;
	}
		return 0;
}


/*
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
*/

二分
二分查找的话,前缀和是满足单调性的,计算从每一个数开始总和刚好大于s的长度。具体实现就是
二分搜索s[i]+s是否存在于前缀和数组中,就是查找以i+1开头的总和刚好大于s的最短长度。

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxn=1e5+5;
int sum[maxn];
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,S;
        cin>>n>>S;
        for(int i=0;i<n;i++)
        {
            int x;
            cin>>x;
            sum[i+1]=sum[i]+x;
        }
        if(sum[n]<S)
        {
            puts("0");
            continue;
        }
        int res=n;
        for(int s=0;sum[s]+S<=sum[n];s++)
        {
            int t=lower_bound(sum+s,sum+n,sum[s]+S)-sum;
            res=min(res,t-s);
        }
        cout<<res<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值