poj - 3061(尺取法)

A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, anda positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of thesubsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.InputMany test cases will be given. 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 lineof the test case, separated by intervals. The input will finish with the end of file.OutputFor each the case the program has to print the result on separate line of the output file.Sample Input10 155 1 3 5 10 7 4 9 2 85 111 2 3 4 5Sample Output23

模板题记录一下。

#include
#include
#include
#define inf 0x3f3f3f3f
using namespace std;
const int mx = 1e5; 
int ans, num[mx], sum, n ,s;
int main(){
	while(scanf("%d%d", &n,&s) != EOF){
		for(int i = 0; i < n; i++)
		  scanf("%d", num + i);
		int st = 0, en = 0, ans = inf, rt;
		sum = 0;
		while(1){
			while(sum < s && en < n)
			  sum += num[en++];
			if(sum < s) break;
			int rt = en - st;
			ans = min(ans, rt);
			 sum -= num[st++];
		}
		if(ans == inf)
		   puts("0");
		else 
		  printf("%d\n", ans);
	}
	
	return 0;
}



你可能感兴趣的:(日常训练)