POJ-3061 Subsequence(维护一个区间)

来源:互联网 发布:linux 进程内存占用 编辑:程序博客网 时间:2024/06/15 16:35

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

挑战程序设计这本书上的一个习题,大致就是求一个最小的区间使得这个区间的和大于S,输出这个区间数的个数。

这里给出了两种做法,一种NlongN的时间复杂度,一种N的时间复杂度,两者的思路都是维护一个(l,r]的区间,然后,不断更新,这个最小值。
第一种代码如下:

/*相当于先利用数组s[i]把[0,i]的和存进去,然后就可以用O(1)的时间复杂度获得任意两个区间的和,然后再从0开始枚举得到一个右边界使得这个区间的和刚好大于S然后不断更新这个最小区间长度就可以得到答案。时间复杂度是nlogn*/#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>using namespace std;const int MAX = 1e5+10;typedef long long ll;int a[MAX],t,n,S;ll s[MAX];void solve(){    int res = n+1;    if(s[n] < S){        cout << 0 << endl;        return;    }    for(int l=0;s[l]+S <= s[n];l++){//相当于是从0开始用二分搜索得到一个最小的右区间,然后左边区间不断枚举.如果值已经很大,区间会不断减小。        int r = lower_bound(s+l,s+n,s[l]+S) - s;//这获得的是(l,r],的一个区间,表明这个区间和是刚好大于S的。        res = min(res,r-l);    }    cout << res << endl;}int main(void){    cin >> t;    while(t--){        memset(s,false,sizeof(s));        cin >> n >> S;        for(int i=1;i<=n;i++){            cin >> a[i];            s[i] = s[i-1] + a[i];        }        solve();    }    return 0;}

第二种代码如下:

/*也是不断维护一个(l,r]的区间注意是左闭右开,使得这个区间的值刚好大于S然后不断从l枚举判断不过这里可以直接得到(l,r]区间的和,所以时间复杂度是接近O(n)的*/#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<set>using namespace std;typedef long long ll;const int MAX = 1e5+10;int a[MAX],n,m;void solve(){    int res = n+1;    ll sum = 0;    int l=0,r = 1;    while(1){        while(r <= n && sum < m)//不断维护这个区间,使得[l,r)这个区间是刚好大于m的            sum += a[r++];        if(sum < m)//如果找不到总和比m大的区间就可以跳出了。因为从当前的l到后面都比m小的话,            break;        res = min(res,r-l);        sum -= a[l++];//相当与是不断缩短区间,即是l不断向右。    }    if(res == n+1)//如果这个值没更新就证明没有结果。        cout << 0 << endl;    else        cout << res << endl;}int main(void){    int t;    cin >> t;    while(t--){        cin >> n >> m;        a[0] = 0;        for(int i=1;i<=n;i++)            cin >> a[i];        solve();    }    return 0;}