icpcarchive 2678 - Subsequence

2678 - Subsequence

A sequence of N positive integers(10 <N < 100 000), each of them less than or equal 10000, and a positive integerS(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 toS.

Input 

Many test cases will be given. For each test case the program has to read the numbersN andS, 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 there isn't such a subsequence, print 0 on a line by itself.

Sample Input 

10 15 
5 1 3 5 10 7 4 9 2 8 
5 11 
1 2 3 4 5

Sample Output 

2 
3


解题思路:该题目,解法不唯一,我这里有两种。一种方法是用队列,存储现在所运用的数列中的数据,当数据有变时,对和进行判断,要是sum>=s,就处理以前入队的数据,要是可以删,就删除(弹出),记录满足要求的队列的最小大小(长度),最后输出结果即可(要是结果为变量初值,要输出”0“).第二种方法是,用动态规划的思想,用数组存储数列中包括该值的前面的值的和,只要sum[i]-sum[j]>=s(i>j),则连续i-j的值的和就是满足sum[]>=s的。


队列解法:

#include<stdio.h>
#include<queue>
using namespace std;
int main()
{
    int n,min1,s,x,y;
    int sum;
    while(scanf("%d%d",&n,&s)!=EOF)
    {
        queue<int> q;
        sum=0;
        min1=0xfffffff;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&x);
            sum+=x;
            q.push(x);   //入队
            y=q.front();
            while(sum-y>=s)   //将距离缩到最短
            {
                sum-=y;
                q.pop();
                y=q.front();
            }
            if(sum>=s&&q.size()<min1)   //找最短距离
                min1=q.size();
        }
        if(min1==0xfffffff)  //若计数变量为初值,直接值0输出
        min1=0;
        printf("%d\n",min1);
    }
    return 0;
}


动态规划思想解法:

#include<stdio.h>
int main()
{
    int n,s;
    int x,min1;
    int i,j;
    int sum[100000];
    while(scanf("%d%d",&n,&s)!=EOF)
    {
        min1=0xfffffff;
        j=0;
        for(i=1;i<=n;i++)
        {
            scanf("%d",&x);
            sum[i]=sum[i-1]+x;
            while(sum[i]-sum[j]>=s)
                j++;
            if(sum[i]-sum[j-1]>=s)
            {
                j--;
                if(i-j<min1)
                min1=i-j;
            }
        }
        if(min1==0xfffffff)
            min1=0;
        printf("%d\n",min1);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值