poj3061(尺取法,前缀和+二分)

本文探讨了寻找连续子序列的最短长度,其元素总和大于或等于给定值S的问题。提供了两种解决方案,一是使用前缀和与二分搜索,复杂度为nlogn;二是采用尺取法,复杂度为n。通过示例输入输出展示了算法的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接 http://poj.org/problem?id=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
题目大意:
比较简单,找最短长度的连续子串的和大于k的长度
思路:
两种解法,一种是前缀和预处理+二分搜索得到答案,复杂度是nlogn
一种是尺取法,复杂度是n
可以参考《挑战程序设计竞赛》p146
尺取法:书上写的代码更加的简介,但我感觉我这个左右指针的移动更加好理解

#include <iostream>
#include <cstdio>
#include <cstring>


using namespace std;
const int maxn=1e5+100;
int a[maxn];
int main()
{
    int t,n,s;
    scanf("%d",&t);
    while(t--)
    {
        memset(a,0,sizeof a);
        scanf("%d%d",&n,&s);
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);

        int l,r,sum,ans,len;
        l=r=0;//左右两个指针
        sum=a[0];//当前串的和
        ans=maxn;//答案
        len=1;//当前串的长度
        if(s==0){printf("0\n");continue;}
        while(1)
        {
            if(sum<s)
            {
                r++;
                if(r>=n) break;
                sum+=a[r];
                len++;
            }
            else
            {
                ans=min(ans,len);
                sum-=a[l];
                len--;
                l++;
                if(l>=n) break;

            }
//            printf("sum=%d\n",sum);
        }
        if(ans==maxn) printf("0\n");
        else
        printf("%d\n",ans);

    }
    return 0;
}
/*
1
5 11
1 2 3 4 5
*/

前缀和+二分

#include<iostream>
#include<algorithm>

using namespace std;
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		int N,S,a[100010],sum[100010]={0};
		cin>>N>>S;
		for(int i=1;i<=N;i++) 
		{
			cin>>a[i];
			sum[i]=sum[i-1]+a[i];//预处理,sum[i]为a[1]到a[i]的和 
		}
		
		if(sum[N]<S) //解不存在 
		{
			cout<<'0'<<endl;continue;
		}
		
		int res=N;
		for(int s=1;sum[s]+S<=sum[N];s++)//枚举起点的位置 
		{
			int t=lower_bound(sum+s+1,sum+N+1,sum[s]+S)-sum;//序列和不小于S的结尾t的最小值
			res=min(res,t-s); //序列长度的最小值 
		}
		cout<<res<<endl;
	} 
}

参考博客 https://blog.youkuaiyun.com/qq_40889820/article/details/82381899

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值