1. 程式人生 > >題解報告:poj 3061 Subsequence(二分前綴法or尺取法)

題解報告:poj 3061 Subsequence(二分前綴法or尺取法)

style esp read ace span 下標 ger finish printf

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
解題思路:這個題可以用二分,但還有一種更優的算法技巧:尺取法,利用兩個下標(起點,終點)不斷放縮像蟲子伸縮爬行一樣來爬出一個最優解。
AC代碼一(79ms):尺取法:時間復雜度是0(n)。
 1 #include<iostream>
 2
#include<algorithm> 3 #include<cstdio> 4 using namespace std; 5 const int maxn=1e5+5; 6 int t,n,S,sum,st,ed,res,a[maxn]; 7 int main(){ 8 while(~scanf("%d",&t)){ 9 while(t--){ 10 scanf("%d%d",&n,&S);sum=st=ed=0;res=maxn; 11 for(int i=0;i<n;++i)scanf("%d",&a[i]); 12 while(1){ 13 while(ed<n&&sum<S)sum+=a[ed++]; 14 if(sum<S)break;//如果當前序列和小於S,直接退出 15 res=min(res,ed-st); 16 sum-=a[st++];//指針st往前走,減去隊首值 17 } 18 if(res>n)res=0; 19 printf("%d\n",res); 20 } 21 } 22 return 0; 23 }

AC代碼二(94ms):二分法:時間復雜度是O(nlogn)。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<string.h>
 5 using namespace std;
 6 const int maxn=1e5+5;
 7 int t,n,S,a[maxn],sum[maxn];
 8 int main(){
 9     while(~scanf("%d",&t)){
10         while(t--){
11             scanf("%d%d",&n,&S);
12             memset(sum,0,sizeof(sum));
13             for(int i=0;i<n;++i)scanf("%d",&a[i]),sum[i+1]=sum[i]+a[i];
14             if(sum[n]<S){puts("0");continue;}//解不存在
15             int res=n;
16             for(int k=0;sum[k]+S<=sum[n];++k){
17                 int ed=lower_bound(sum+k,sum+n+1,sum[k]+S)-sum;
18                 res=min(res,ed-k);
19             }
20             printf("%d\n",res);
21         }
22     }
23     return 0;
24 }

題解報告:poj 3061 Subsequence(二分前綴法or尺取法)