POJ3061 Subsequence

POJ3061 Subsequence

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

1
2
3
4
5
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5

Sample Output

1
2
2
3

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <cstdio>
#include <algorithm>

using namespace std;

const int MAX_N = 100050;

int a[MAX_N], sum[MAX_N];

int main() {
int k, n, S;
scanf("%d", &k);
while (k--) {
scanf("%d %d", &n, &S);
for (int i = 0; i < n; ++i)
scanf(" %d", &a[i]);

// Ans1 Start
sum[0] = a[0];
for (int i = 1; i < n; ++i)
sum[i] = sum[i-1] + a[i];
if (sum[n-1] < S) {
printf("0\n");
continue;
}
int res = n;
for (int s = 0; sum[s] + S <= sum[n-1]; ++s) {
res = min(res, lower_bound(sum+s, sum+n, sum[s]+S)-sum-s);
}
printf("%d\n", res);
// Ans1 End
// Ans2 Start
int res = n + 1, t = 0, sum = 0;
for(int s = 0; s < n; ++s) {
while (t < n && sum < S) {
sum += a[t++];
}
if (sum < S) break;
res = min(res, t-s);
sum -= a[s];
}
if (res > n) {
res = 0;
}
printf("%d\n", res);
// Ans2 End
}
return 0;
}

Analysis

  1. 求长度最小的子序列,其序列和不小于 S
  2. 法1:建立 sum 数组,则 \(sum[j]-sum[i]\) 就是连续的序列和,用二分搜索法降低复杂度。
  3. 法2:若 \(a_s+...+a_t\) 是以 \(a_s\) 开始总和不小于 S 的最短序列,则 \(a_{s+1}+...+a_{t-1} <a_s+...+a_{t-1}<S\) ,则每次中间的\(a_{s+1}+...+a_{t-1}\) 不用再次计算,直接使用即可,降低了复杂度。
# POJ

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×