1. 程式人生 > >POJ 3061 Subsequence 尺取法

POJ 3061 Subsequence 尺取法

can each 0ms sample mis accep AC problem map

題目:

Subsequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 18528 Accepted: 7921

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

Southeastern Europe 2006

題意:給定一個整數序列,求總和不小於S的最短連續子序列的長度。

思路:兩種想法:(1)計算出第i位的前綴和。然後二分查找答案 O(nlogn) (2)尺取法,超過S後,前面開始減小,如果仍然滿足條件 更新結果,否則繼續向後增加。

代碼:

技術分享圖片
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<iostream>
 5 #include<string>
 6 #include<vector>
 7 #include<stack>
 8 #include<bitset>
 9 #include<cstdlib>
10 #include<cmath>
11 #include<set>
12 #include<list>
13 #include<deque>
14 #include<map>
15 #include<queue>
16 using namespace std;
17 typedef long long ll;
18 const double PI = acos(-1.0);
19 const double eps = 1e-6;
20 const int INF = 0x3f3f3f3f;
21 
22 const int MAXN = 1e5+10;
23 int a[MAXN];
24 int n = 0;
25 int S = 0;
26 
27 void solve(){
28     int res = n+1;
29     int s = 0;int t= 0;int sum =0;
30     for(;;){
31         while(t<n&&sum<S){
32             sum+=a[t++];
33         }
34         if(sum<S)    break;
35         res = min(res,t-s);
36         sum-=a[s++];
37     }
38     if(res>n){
39         printf("0\n");
40     }else{
41         printf("%d\n",res);
42     }
43 }
44 
45 int main(){
46     int T = 0;
47     scanf("%d",&T);
48     for(int t=0;t<T;t++){
49         scanf("%d %d",&n,&S);
50         for(int i=0;i<n;i++){
51             scanf("%d",&a[i]);
52         }
53         solve();
54     }
55     
56     return 0;
57 }
View Code

POJ 3061 Subsequence 尺取法