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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_40733911/article/details/98845975

题目链接 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.csdn.net/qq_40889820/article/details/82381899

猜你喜欢

转载自blog.csdn.net/qq_40733911/article/details/98845975