Description
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
Source
题意:给你n个数,和S,要求在n个数中找一个区间,使区间和大于S,且这个区间长度最小。
题解:经典简单题目,可以使用二分法或尺取法。
一、二分
计算前缀和,枚举每个元素,作为区间的起始点,并在之后的前缀数组中进行二分法,当s[mid]-s[i]>S时,左区间查找,反之右区间,记录最小的mid-i+1;
1 #include <stdio.h> 2 #include <iostream> 3 #include <algorithm> 4 #include <string.h> 5 using namespace std; 6 7 const int INF = 2147483647; 8 int a[100010]; 9 int main() 10 { 11 int S, t, n; 12 int T, mi; 13 int l, r, mid; 14 while(cin >> T) 15 { 16 while(T--) 17 { 18 cin >> n >> S; 19 for(int i = 1; i <= n; i++) 20 { 21 scanf("%d", &t); 22 if(i == 1) 23 a[i] = t; 24 else 25 a[i] = a[i-1] + t; 26 } 27 28 a[0] = 0; 29 mi = INF; 30 for(int i = 1; i <= n; i++) 31 { 32 l = i; 33 r = n; 34 while(l <= r) 35 { 36 mid = (l + r)/2; 37 if( a[mid] - a[i-1] >= S) 38 { 39 if( mi > mid-i+1 ) 40 mi = mid - i + 1; 41 r = mid - 1; 42 } 43 else 44 { 45 l = mid + 1; 46 } 47 } 48 } 49 if(mi == INF) 50 printf("0\n"); 51 else printf("%d\n", mi); 52 53 54 55 } 56 } 57 return 0; 58 }
二、尺取
先取前x个数(r++),直到大于S,减去该区间最前面的一个数(收缩 l++),再次判断是否大于S,重复操作,直至t==n或 取得的区间无法大于S 停止。
1 #include <stdio.h> 2 #include <iostream> 3 #include <algorithm> 4 #include <string.h> 5 using namespace std; 6 7 int a[100010]; 8 const int INF = 2147483647; 9 int main() 10 { 11 int T, n, S, sum; 12 int l, r, mi; 13 14 while(cin >> T) 15 { 16 while(T--) 17 { 18 cin >> n >> S; 19 for(int i = 0; i < n; i++) 20 { 21 scanf("%d", a + i); 22 } 23 24 l = r = sum = 0; 25 mi = INF; 26 for(;;) 27 { 28 while(r < n && sum < S) 29 { 30 sum += a[r++]; 31 } 32 if( sum < S) 33 break; 34 else 35 { 36 mi = min(mi, r - l); 37 sum -= a[l++]; 38 } 39 } 40 41 42 if(mi == INF) 43 printf("0\n"); 44 else printf("%d\n", mi); 45 } 46 } 47 return 0; 48 }