poj 3061 (挑战程序设计竞赛3.2.1)

Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 10068   Accepted: 4096

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
1.尺区法
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define N 101000
#define inf 0x3f3f3f3f
int a[N];
int main()
{
#ifdef CDZSC
	freopen("i.txt", "r",stdin);
#endif
	int t, n, s;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d%d", &n, &s);
		for (int i = 1; i <= n; i++)
			scanf("%d", a + i);
		int l=1, r=1, ans = inf,sum=0;
		while (true)
		{
			while (sum < s&&r <= n)
			{
				sum += a[r++];
			}
			if (sum < s)break;
			ans = min(ans, r - l);
			sum -= a[l++];
		}
		printf("%d\n", ans == inf ? 0 : ans);
	}
	return 0;
}

2.二分
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define N 101000
#define LL long long
#define inf 0x3f3f3f3f
int a[N];
LL sum[N];
int main()
{
#ifdef CDZSC
	freopen("i.txt", "r", stdin);
#endif
	int n, t, s,ans;
	scanf("%d", &t);
	while (t--)
	{
		ans = inf;
		memset(sum, 0, sizeof(sum));
		scanf("%d%d", &n, &s);
		for (int i = 1; i <= n; i++)
			scanf("%d", a + i);
		for (int i = 0; i < n; i++)
			sum[i + 1] = sum[i] + a[i+1];
		if (sum[n] < s)ans = 0;
		for (int i = 1; sum[i] + s <= sum[n]; i++)
		{
			int w = lower_bound(sum + 1, sum + n, sum[i] + s) - sum;
			ans = min(ans, w - i);
		}
		printf("%d\n", ans);
	}
	return 0;
}

你可能感兴趣的:(poj 3061 (挑战程序设计竞赛3.2.1))