poj3061 Subsequence(尺取法)

Subsequence
Time Limit: 1000MS      Memory Limit: 65536K
Total Submissions: 14033        Accepted: 5936
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
先求出前缀和,然后跑遍尺取法就好了。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<ctime>
#include<string>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#include<set>
#include<map>
#include<cstdio>
#include<limits.h>
#define MOD 1000000007
#define fir first
#define sec second
#define fin freopen("/home/ostreambaba/文档/input.txt", "r", stdin)
#define fout freopen("/home/ostreambaba/文档/output.txt", "w", stdout)
#define mes(x, m) memset(x, m, sizeof(x))
#define Pii pair<int, int>
#define Pll pair<ll, ll>
#define INF 1e9+7
#define inf 0x3f3f3f3f
#define Pi 4.0*atan(1.0)

#define lowbit(x) (x&(-x))
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-9;
const int maxn = 1e5+5;
using namespace std;

inline int read(){
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int sum[maxn];
int k[maxn];
int main(){
  //  fin;
    int Case=read();
    while(Case--){
        int n,m;
        mes(sum,0);
        n=read(),m=read();
        for(int i=1;i<=n;++i){
            k[i]=read();
            sum[i]=sum[i-1]+k[i];
        }
        int t=1,s=1,res=inf,re=0;
        for(;;){
            while(t<=n+1&&re<m){
                re=sum[t]-sum[s-1];
                ++t;
            }
            if(re<m){
                break;
            }
            res=min(res,t-s);
            re-=k[s];
            ++s;
        }
        if(res!=inf){
            printf("%d\n",res);
        }else{
            puts("0");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/viscu/article/details/69396828