首页 > 代码库 > POJ3061 Subsequence

POJ3061 Subsequence

题目大意:给定长度为n的整列整数a[0],a[1],……a[n-1],以及整数S,求出总和不小于S的连续子序列的长度的最小值。

PS:用二分或者直尺法。省赛热身。

#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
const int INF = 0x3fffff;
vector<int> v;
int n, S;

int work() {
	int ans = INF;
	int l=0, r = 0;
	int sum = 0;
	for(int i = 0; i < n && sum < S; i++) {
		sum += v[i];
		r = i;
	}
	if(sum < S) return 0;
	while(r < n && l <= r) {
	    if(sum<S && r < n) {
			sum += v[++r];
		}
		if(sum >= S && r<n) {
			ans = min(ans, r-l+1);
			sum = sum - v[l++];
		}
	}
	return ans;
}

int main()
{
	int T;
	//freopen("in", "r", stdin);
	scanf("%d", &T);
	int t;
	while(T--) {
		scanf("%d%d", &n, &S);
		v.clear();
		for(int i = 0; i < n; i++) {
			scanf("%d", &t);
			v.push_back(t);
		}
		int res = work();
		printf("%d\n", res);
	}
    return 0;
}