標籤:
傳送門
Subsequence
| Time Limit: 1000MS |
|
Memory Limit: 65536K |
| Total Submissions: 11284 |
|
Accepted: 4694 |
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
210 155 1 3 5 10 7 4 9 2 85 111 2 3 4 5
Sample Output
23
Source
Southeastern Europe 2006
題目大意:
給定T組資料,每組資料有一個數n,表示有n個數,然後再給定一個數S,讓你求這個數列總和>=S的長度的最小值。(資料範圍 n<1e5,S<1e8,a[i]<=1e4)
解題思路:
(1)首先說一下複雜度為 O(n*log(n))的演算法
因為所有的元素都是>0的,所以我們可以想到的是假設數列 ai ai+1 ai+2 ....at-1 的和>=S,那麼我們可以求一下這些數列的前i項和,現在定義sum[i]為a0 a1 a2 ...ai-1的,那麼ai ai+1 ai+2 ... at-1 就可以寫成 sum[t] - sum[i], 因為 sum[t]-sum[i] >= t,那麼我們要求的是這些長度的最小值,所以就是 t-i 的最小值,那麼我們可以先預先處理計算sum[i]的值,然後在可以進行二分演算法求 t-i 的最小值
My Code:
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MAXN = 100000+5;int a[MAXN],sum[MAXN];int n;void get_Sum(){ sum[0] = 0; for(int i=0; i<n; i++) sum[i+1] = sum[i] + a[i];}int main(){ int T,S; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&S); for(int i=0; i<n; i++) scanf("%d",&a[i]); get_Sum(); if(sum[n] < S) puts("0"); else { int ans = n + 100; for(int i=0; sum[i]+S<=sum[n]; i++) { int tmp = lower_bound(sum+i,sum+n,S+sum[i])-sum; ans = min(ans,tmp-i); } cout<<ans<<endl; } } return 0;}
(2)複雜度為 O(n)的演算法
現在就得說一下尺取法了,其實尺取法的關鍵就是兩個指標都是從頭開始的,兩個指標s, t,if(sum<S)那麼sum+=a[t],t++;否則的話,sum -= a[s],s++;抓住這個關鍵就行了,在不滿足條件的時候不要忘記更新 ans,ans始終是s-t的最小值。。。
My Code:
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MAXN = 100000+5;int a[MAXN];int main(){ int T,S,n; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&S); for(int i=0; i<n; i++) scanf("%d",&a[i]); int t=0, s=0, sum=0; int ans = n + 100; while(1) { while(t<n && sum<S) { sum += a[t]; t++; } if(sum < S) break; ans = min(ans, t-s); sum -= a[s]; s++; } if(ans == n+100) puts("0"); else { cout<<ans<<endl; } } return 0;}
POJ 3061 Subsequence(尺取法)