POJ3061 Subsequence

简介: POJ3061 Subsequence

POJ3061 Subsequence 这道题是POJ上id为3061的一道题,这道题总体来说比较简单,但是坑点也不少额,稍微不注意就WA了,好了,我们一起来看看题意吧:

我们先看下中文大致题意吧:

给定长度为n的正整数数列以及正整数S,求出总和不小于S的连续子串的长度的最小值,如果解不存在,则输出 0

下面的描述是来自POJ官网

题目描述

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.

输入描述

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.

输出描述

For each the case the program has to print the result on separate line of the output file.if no answer, print 0.

示例1

输入

2

10 15

5 1 3 5 10 7 4 9 2 8

5 11

1 2 3 4 5

输出

2

3

题目链接: POJ3061 Subsequence

思路:

这道题最最暴力的做法就是n2的时间复杂度,n2是会TLE(超时)的,应该进行优化,怎么优化呢,我们比较容易想到双指针算法!

我们来看看成功AC的代码吧:

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int t;
int n,s;
int a[100010];
int main(){
    cin>>t;
    while(t--){
        cin>>n>>s;
        memset(a,0,sizeof(a));
        for(int i=1;i<=n;i++) cin>>a[i];
        int r=0;
        int su=0;
        int len=n+1;
        for(int i=1;i<=n;i++){
            while(r<=n&&su<s){
                r++;
                su+=a[r];
            }
            if(su>=s) len=min(len,r-i+1);
            su-=a[i];
        }
        if(len>n) cout<<"0\n";
        else cout<<len<<"\n";
    }
    return 0;
}


相关文章
|
11月前
|
算法
poj 1159 Palindrome(最长公共子串)
关于求最长公共子串, 用到的是动态规划
30 0
|
索引
LeetCode 392. Is Subsequence
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
94 0
LeetCode 392. Is Subsequence
LeetCode 376. Wiggle Subsequence
如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
88 0
LeetCode 376. Wiggle Subsequence
HDU 4632 Palindrome subsequence(动态规划)
HDU 4632 Palindrome subsequence(动态规划)
67 0
HDU 4632 Palindrome subsequence(动态规划)
HDU-1061,Rightmost Digit(快速幂)
HDU-1061,Rightmost Digit(快速幂)
[HDU 4738] Caocao‘s Bridges | Tarjan 求割边
Problem Description Caocao was defeated by Zhuge Liang and Zhou Yu in the battle of Chibi. But he wouldn’t give up. Caocao’s army still was not good at water battles, so he came up with another idea. He built many islands in the Changjiang river,
134 0
POJ 1306 Combinations
POJ 1306 Combinations
109 0
|
机器学习/深度学习