Question link: http://poj.org/problem? Id = 3061
Let's talk about the simplest algorithm, that is, for nesting. The complexity is that O (N ^ 3) is too slow, so you don't have to think about it. Next, some people may think of the Binary Search idea and optimize the time complexity to O (N * logn). I tried to use AC.
However, this is not the focus of today's speech. Today we will talk about the ruler acquisition method, a common Skill Method Used in ACM competitions. This is an algorithm that can directly optimize the time complexity to O (n.
Let's first introduce the ruler acquisition method. As the name suggests, a ruler can be captured in one piece like a ruler. Is it a bit confusing to explain it ~.. It doesn't matter. Let's use this question to appreciate the charm of the ruler acquisition method.
Question Translation:
The numbers of numbers A0, A1, A2, A3... an-1 and s with the given length of N. Obtain the minimum value of the length of a continuous subsequence that is not less than S. If the solution does not exist, 0 is output.
Restrictions:
10 <n <10 ^ 5
0 <AI <10 ^ 4
S <10 ^ 8
Here we take the first group of test data for example, n = 10, S = 15, A = {5, 1, 3, 5, 10, 7}
This figure shows how to "Fetch" the ruler.
The entire process is divided into four parts:
1. initialize the Left and Right endpoints
2. Expand the right endpoint until the conditions are met.
3. If the conditions cannot be met in step 2, terminate the operation. Otherwise, update the result.
4. Expand the left endpoint by 1 and return to step 2.
The ruler acquisition method is used to optimize the complexity to O (n ).
Finally, let's give a definition of the ruler acquisition method to better understand: the return start and end of the advancing interval, and the method for finding the minimum interval that meets the conditions is called the ruler acquisition method.
Let's end with the AC code for this question...
#include <iostream>#include <algorithm>using namespace std;int a[100001];int main(){ int x,y; int t; int res; int num; int l,r; int sum; cin>>num; while(num--) { sum = 0; res = 999999999; cin>>x>>y; for(int i=1;i<=x;i++) { cin>>a[i]; } r = 1; l = 1; for(;;) { while(r<=x&&sum<y) { sum += a[r]; r++; } if(sum<y) break; res = min(res,r-l); sum -= a[l]; l++; } if(res==999999999) res = 0; cout<<res<<endl; } return 0;}
How to get a ruler from a specific question: poj 3061 subsequence