[POJ 3061] Subsequence (尺取法)

Link

http://poj.org/problem?id=3061

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.

 给定一个 n n n个整数的序列,求长度最小的区间和大于等于 S S S的区间。

Solution

 使用两个指针维护这样一个区间和大于 S S S的区间,每次维护之后,使用一个 m a x n maxn maxn变量来记录,满足区间和大于等于 S S S的最小区间。

 记录前缀和 s u m sum sum,那么 s u m sum sum是递增的。那么 [ l , r ] [l,r] [l,r]的区间和就是 s u m [ r ] − s u m [ l − 1 ] sum[r]-sum[l-1] sum[r]sum[l1],如果当前指针指向的区间的区间和大于等于 S S S,说明它这个区间是满足需求的,我们用它来更新一下表示长度的 m a x n maxn maxn,然后让左指针右移,进行下一个区间的查找;反之如果,区间和小于 S S S,我们就让右向右移来调整这个区间和直到它再一次大于等于 S S S,然后我们就可以再次更新。

Code
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
//#include<unordered_map>
using namespace std;

#define maxn 100900
#define inf 0x3f3f3f3f
typedef long long ll;
struct edge{
    int u,v,next,w; 
}e[2];

int head[1],cnt;
void add(int x,int y,int w){
    e[cnt].u=x;
    e[cnt].v=y;
    e[cnt].w=w;
    e[cnt].next=head[x];
    head[x]=cnt++;
    e[cnt].u=y;
    e[cnt].v=x;
    e[cnt].w=w;
    e[cnt].next=head[y];
    head[y]=cnt++;
}

int read(){
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-')f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        x=x*10+c-'0';
        c=getchar();
    }
    return x*f;
}
int t,n,s,a[maxn],sum[maxn];
int main(){
    t=read();
    while(t--){
        memset(sum,0,sizeof(sum));
        n=read(),s=read();
        for(int i=1;i<=n;i++)
            a[i]=read(),sum[i]=sum[i-1]+a[i];
        int L=1,R=1,res=inf;
        while(L<=n&&L<=R&&R<=n){
            if(sum[R]-sum[L-1]>=s)
                res=min(R-L+1,res),L++;
            else R++;

        }
        if(res==inf)cout<<0<<endl;
        else cout<<res<<endl;
    }
}

我们坚持一件事情,并不是因为这样做了会有效果,而是坚信,这样做是对的。
——哈维尔

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值