SEERC 2006 / UVa 1121 Subsequence (有和下界的最短连续子序列)

1121 - Subsequence

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=460&page=show_problem&problem=3562

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 

Many test cases will be given. 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 there isn't such a subsequence, print 0 on a line by itself.

Sample Input 

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

Sample Output 

2 
3

题意:给一个正整数序列An和正整数S,求最短的连续序列,它们的和>=S。


思路:

形象点说,就像你堆积木,超过一定值S后我们就把最下面的几块积木去掉。

具体方法是从前面开始不断累加,当和值超过S时减少前面的数值,然后记录下刚好>=S的ans值,如此重复直到序列尾,输出最小的ans。

复杂度:O(n)  (就相当于扫描了一遍序列,况且代码中的i值是不断增加的)


完整代码:

/*0.042s*/

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100010;

int A[maxn], B[maxn];

int main(void)
{
	int n, S;
	while (~scanf("%d%d", &n, &S))
	{
		for (int i = 1; i <= n; i++) 
            scanf("%d", &A[i]);
		B[0] = 0;
		for (int i = 1; i <= n; i++) 
            B[i] = B[i - 1] + A[i];
		int ans = n + 1;
		int i = 1;
		for (int j = 1; j <= n; j++)
		{
			if (B[i - 1] > B[j] - S) 
                continue; // 没有满足条件的i,换下一个j
			while (B[i] <= B[j] - S) 
                i++; // 求满足B[i-1]<=B[j]-S的最大i
			ans = min(ans, j - i + 1);
		}
		printf("%d\n", ans == n + 1 ? 0 : ans);
	}
	return 0;
}

你可能感兴趣的:(C++,ACM,uva)