POJ - 3061 Subsequence

原创 2013年12月01日 19:57:21

题意:求一个有n个正整数组成的序列,给定整数S,求长度最短的连续序列,使得它们的和大于等于S

思路:第一种方法:用二分找到满足B[j]-B[i] >= S的最小的长度,复杂度O(nlogn)

第二种方法:由于j是递增的,B[j]也是递增的,所以B[i-1]<=B[j]-S的右边也是递增的,也就是说满足条件的i的位置也是递增的

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 100005;

int A[MAXN],B[MAXN];
int n,S;

int main(){
    int t;
    scanf("%d",&t);
    while (t--){
        scanf("%d%d",&n,&S);
        for (int i = 1; i <= n; i++)
            scanf("%d",&A[i]);
        B[0] = 0;
        for (int i = 1; i <= n; i++)
            B[i] = B[i-1] + A[i];
        int ans = n+1;
        for (int j = 1; j <= n; j++){
            int i = lower_bound(B,B+j,B[j]-S) - B;
            if (i > 0)
                ans = min(ans,j-i+1);
        }
        printf("%d\n",(ans == n+1) ? 0 : ans);
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN = 100005;

int A[MAXN],B[MAXN];
int n,S;

int main(){
    int t;
    scanf("%d",&t);
    while (t--){
        scanf("%d%d",&n,&S);
        for (int i = 1; i <= n; i++)
            scanf("%d",&A[i]);
        B[0] = 0;
        for (int i = 1; i <= n; i++)
            B[i] = B[i-1] + A[i];
        int i = 1,ans = n+1;
        for (int j = 1; j <= n; j++){
            if (B[i-1] > B[j] - S)
                continue;
            while (B[i] <= B[j] - S)
                i++;
            ans = min(ans,j-i+1);
        }
        printf("%d\n",(ans == n+1) ? 0 : ans);
    }
    return 0;
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

POJ - 3061 Subsequence

Subsequence Time Limit: 1000MS   Memory Limit: 65536KB   64bit IO Format: %lld & %llu Submi...

POJ - 3061 Subsequence(前缀和+二分和尺取法)

题意:给定长度为n的整数数列a0,a1,…,an-1以及整数S。求出总和不小于S的连续子序列的长度的最小值。如果解不存在,输出0。 思路: 1. 可以用O(n)的时间算好前缀和,之后就能在O(1)的时...

POJ 3061 Subsequence (尺取法)

A - Subsequence Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %l...

POJ - 3061 Subsequence(尺取法)

Subsequence Time limit 1000 ms Memory limit 65536 kBDescription A sequence of N positive integers ...

【POJ - 3061】Subsequence

Subsequence Subsequence Time Limit: 1000MS   Memory Limit: 65536K Total Sub...

POJ:3061 Subsequence(尺取法)

A - Subsequence Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %...

POJ 3061 Subsequence (二分查找)

Description A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 1...

poj 3061 Subsequence 取尺法

传送门:poj 3061 Subsequence题目大意给定长度为n的数列整数a0,a1,a2…an-1以及整数S。求出总和不小于S的连续子序列的长度的最小值,如果解不存在输出0解题思路先介绍一下取尺...

POJ - 3061 Subsequence(前缀和+二分和尺取法)

Subsequence Time Limit: 1000MS   Memory Limit: 65536KB   64bit IO Format: %I64d & %I64u...

POJ3061 Subsequence(双指针)

题目链接:http://poj.org/problem?id=3061 Subsequence Time Limit: 1000MS   Memory Limi...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)