zoukankan      html  css  js  c++  java
  • POJ-3061 Subsequence(队列求区间和)

    Subsequence

     

    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

    题目大意:输入为一组n个正整数(10<n <100000),和一个正整数s(s<100000000)。编写一个程序找到序列的连续元素的子序列的最小长度,使其的总和大于或等于s。

     1 #include<stdio.h>
     2 
     3 #define maxn 100005
     4 #define min(a,b) (a<b?a:b)
     5 
     6 int n, s;
     7 int a[maxn];
     8 
     9 int min_length()
    10 {
    11     int sum = 0, i = 0, j;
    12     int minx = 0x3f3f3f3f;
    13     for (j = 0; j < n;)                //遍历每个元素
    14     {
    15         while (sum < s && j < n)
    16         {
    17             sum += a[j++];           //从头开始一个一个加,如果<s,则一直加
    18         }
    19         while (sum >= s)
    20         {
    21             minx = min(minx,j - i);         //j-i为这一段相加的长度
    22             sum -= a[i++];                //在sum中减去最前面的一个元素值,在一开始减去a[0],之后a[1],a[2]……都要逐个减去。
    23                                            //如n = 4, s = 5,序列为1 2 2 3,1+1+2=5后minx=3,j=3;minx=3,sum=5-1=4,i=1;
    24                                            //sum=4+3=7,j=4;minx=3,sum=7-2=5,i=2;minx=2,sum=5-2=3,i=3;以计算最小长度)
    25         }
    26     }
    27     if (minx == 0x3f3f3f3f)
    28         return 0;
    29     else 
    30         return minx;
    31 }
    32 
    33 int main()
    34 {
    35     int i, t;
    36     scanf("%d", &t);
    37     while (t--)
    38     {
    39         scanf("%d%d", &n, &s);
    40         {
    41             for (i = 0; i < n; i++)
    42                 scanf("%d", &a[i]);
    43             printf("%d
    ", min_length());
    44         }
    45     }
    46     return 0;
    47 }
  • 相关阅读:
    iOS中3种正则表达式的使用
    iOS 正则表达式
    Autolayout-VFL语言添加约束-备
    PHP一个最简单的CMS内容管理系统
    国外主流PHP框架比较
    PHP中的ob_start() 的使用
    jpGraph的应用及基本安装配置 BY 命运
    未能加载文件或程序集“Common”或它的某一个依赖项。试图加载格式不正确的程序
    Android手机 Fildder真机抓包
    axWindowsMediaPlayer1获取音频长度
  • 原文地址:https://www.cnblogs.com/youdiankun/p/3423966.html
Copyright © 2011-2022 走看看