首页 > 其他 > 详细

UVA 12697 Minimal Subarray Length

时间:2014-08-23 16:43:01      阅读:214      评论:0      收藏:0      [点我收藏+]

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.

 

bubuko.com,布布扣
 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\n",ans);
41     }
42     return 0;
43 }
View Code

 

UVA 12697 Minimal Subarray Length

原文:http://www.cnblogs.com/crackpotisback/p/3931383.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!