zoukankan      html  css  js  c++  java
  • UVA 12697 Minimal Subarray Length

    Minimal Subarray Length

    Time Limit: 3000ms
    Memory Limit: 131072KB
    This problem will be judged on UVALive. Original ID: 6609
    64-bit integer IO format: %lld      Java class name: Main
     
     

    You are given an integer sequence of length N and another value X. You have to find a contiguous subsequence of the given sequence such that the sum is greater or equal to X. And you have to find that segment with minimal length.

    Input

    First line of the input file contains T the number of test cases. Each test case starts with a line containing 2 integers N (1 ≤ N ≤ 500000) and X (−109 ≤ X ≤ 109). Next line contains N integers denoting the elements of the sequence. These integers will be between −109 to 109 inclusive.

    Output

    For each test case output the minimum length of the sub array whose sum is greater or equal to X. If there is no such array, output ‘-1’.

    Sample Input

    3
    5 4
    1 2 1 2 1
    6 -2
    -5 -6 -7 -8 -9 -10
    5 3
    -1 1 1 1 -1

    Sample Output

    3
    -1
    3

    解题:先求和。维护一个队列,下标单调,值也单调。对于i,j.如果sum[i] <= sum[j] && i > j ,那么i肯定比j好。去掉j.

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <cmath>
     5 #include <algorithm>
     6 #include <climits>
     7 #include <vector>
     8 #include <queue>
     9 #include <cstdlib>
    10 #include <string>
    11 #include <set>
    12 #include <stack>
    13 #define LL long long
    14 #define pii pair<int,int>
    15 #define INF 0x3f3f3f3f
    16 using namespace std;
    17 const int maxn = 500100;
    18 LL sum[maxn] = {0};
    19 int n,x,inc[maxn];
    20 int main() {
    21     int t,i,lt,rt,ans;
    22     scanf("%d",&t);
    23     while(t--){
    24         scanf("%d %d",&n,&x);
    25         for(i = 1; i <= n; i++){
    26             scanf("%lld",sum+i);
    27             sum[i] += sum[i-1];
    28         }
    29         lt = 0;
    30         inc[0] = rt = 1;
    31         ans = n+1;
    32         for(i = 2; i <= n; i++){
    33             while(lt < rt && sum[i] <= sum[inc[rt-1]]) rt--;
    34             inc[rt++] = i;
    35             while(lt + 1 < rt && sum[i] - sum[inc[lt]] >= x){
    36                 ans = min(ans,i-inc[lt]);
    37                 lt++;
    38             }
    39         }
    40         ans == n+1?puts("-1"):printf("%lld
    ",ans);
    41     }
    42     return 0;
    43 }
    View Code
  • 相关阅读:
    9、SpringMVC:Ajax技术(扩展:百度搜索框提示应用)
    8、SpringMVC:整合SSM
    SpringMVC:多视图解析器配置以及问题
    7、SpringMVC:JSON讲解
    IDEA中lombok的插件配置及使用
    C语言编程练习23:美丽数
    C语言编程练习45:ACM CLUB晚会
    C语言编程练习22:2^x mod n = 1
    C语言编程练习21:找规律填数字
    C语言编程练习20:计算合并
  • 原文地址:https://www.cnblogs.com/crackpotisback/p/3931383.html
Copyright © 2011-2022 走看看