poj-3061-Subsequence(二分前缀和or尺取法)

Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 19722   Accepted: 8429

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

题意:给你n个一连串的数字,求不小于m的最短的连续的数字长度;

二分思路:涉及到几个数据之和,就会很自然地想到前缀和哦,用数组s[i]表示前缀和,下标从1开始存,即s[0]=0,s[1]=a[1],s[2]=s[1]+a[2], .....;

如果s[n]<k,说明所有数据的和就小于k,那么肯定不符合条件,直接输出0,continue;数组s[i]一定是递增的,是按照一定顺序排列的,所以对于s[i]可以使用二分查找的思路。

#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
int sum[100005];
int main()
{
    int n,t,s,k,ans,res;
    cin >> t;
    while(t--)
    {
        cin >> n >> s;
        sum[0] = 0; ans = 100005;
        for(int i = 1; i <= n; i++)
        {
            cin >> sum[i];
            sum[i] += sum[i-1]; //将数组求和是常用的技巧
        }
        if(sum[n] < s)
        {
            cout << "0" << endl;
            continue;
        }
        for(int k = 0; sum[n] - sum[k] >= s; k++) //枚举起点
        {
            res = lower_bound(sum+k,sum+n+1,sum[k]+s)-(sum+k); //第一个大于等于该值的位
            if(res < ans) ans = res;
        }
        cout << ans << endl;
    }
}
尺取法:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define maxn 100005
#define INF 0x3f3f3f3f
int a[maxn];
int main()
{
	int t, n, s, ans;
	scanf("%d",&t);
	while(t--)
	{
		ans = INF;
		scanf("%d%d",&n,&s);
		for(int i = 0; i < n; i++)
            scanf("%d",&a[i]);
		int r = 0, l = 0, sum = 0;
		while(1)
		{
			while(r < n && sum < s)
			{
				sum += a[r];
				r++;
			}
			if(sum < s) break;
			ans = min(ans,r-l);
			sum -= a[l];
			l++;
		}
		if(ans == INF)
            printf("0\n");
		else
            printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/sugarbliss/article/details/80975028