POJ3061 -- Subsequence 尺取法 or 二分+前缀和

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


二分:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int len=1e5+3;
const int INF=0x3f3f3f3f;
#define ll long long
int num[len];
int sum[len];
int main()
{
	int n,S,t;
	cin>>t;
	while(t--)
	{
		scanf("%d%d",&n,&S);
		fill(sum,sum+n,0);
		for(int i=0;i<n;++i)
			scanf("%d",num+i);
		sum[0]=num[0];
		for(int i=1;i<n;++i)
			sum[i]=sum[i-1]+num[i];
			//利用前缀和 
		if(sum[n-1]<S)//总和小于S 
		{
			puts("0");
			continue;
		}
		int minm=INF;
		for(int i=0;S+sum[i]<=sum[n-1];++i)
		{
			int t=lower_bound(sum,sum+n,S+sum[i])-sum;
			//当sum[x]>=sum[i]+S时,即sum[x]-sum[i]>=S,即num[i+1]+num[i+2]+...+num[x]>=S; 
			minm=min(minm,t-i);
		}
		cout<<minm<<endl;
	}
}

尺取:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int len=1e5+3;
const int INF=0x3f3f3f3f;
#define ll long long
int num[len];
int main()
{
	int n,S,t;
	cin>>t;
	while(t--)
	{
		scanf("%d%d",&n,&S);
		for(int i=0;i<n;++i)
			scanf("%d",num+i);
		int s=0,t=0,minm=INF;
		int sum=0;
		while(1)
		{
			while(t<n&&sum<S)//注意条件2 
			{
				sum+=num[t];
				t++;	
			}
			if(sum<S)break;//利用条件2来结束循环 
			minm=min(minm,t-s);
			sum-=num[s];
			s++;
		}
		if(s==0&&t==n)puts("0");
		else printf("%d\n",minm);
	}
}

 
 

猜你喜欢

转载自blog.csdn.net/hutwuguangrong/article/details/80251205