Selected Topics I 2019_GDUT_ newborn A- feet take POJ-3061

topic:

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

Analysis: Size emulated, two variable analogue scale head and foot tail, from the first element of the rear foot tail constantly shift start looking, when they are found sub-sequence of the first string of qualifying save the answer, then after a shift-foot head bit, re-find and compare to find the answer and the answer has been, until the head to the foot or foot end of the last element to the last element has been so far, but the current sequence and lack of s.
Code:

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
	int t,n,s,a[100001];
	cin>>t;
	while (t--)
	{
		cin>>n>>s;
		for (int i=1;i<=n;i++)
		scanf("%d",a+i);
		int l=1,r=1;
		int ans=2147483647,sum=0;
		while (l<=n)
		{
			while (sum<s && r<=n)
			{
				sum+=a[r];
				r++;
			}
			if (sum<s)
			break;
			if (r-l<ans) ans=r-l;
			sum-=a[l];
			l++;
		}
		if (ans>n) cout<<0<<endl;
		else
		cout<<ans<<endl;
	}
}
Published 14 original articles · won praise 0 · Views 311

Guess you like

Origin blog.csdn.net/qq_39581539/article/details/103963766