您的位置:首页 > 其它

UVA 12697 Minimal Subarray Length

2014-08-23 16:03 656 查看

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.

[b]Input[/b]

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.

[b]Output[/b]

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’.

[b]Sample Input[/b]

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

[b]Sample Output[/b]

3
-1
3

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

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <climits>
#include <vector>
#include <queue>
#include <cstdlib>
#include <string>
#include <set>
#include <stack>
#define LL long long
#define pii pair<int,int>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 500100;
LL sum[maxn] = {0};
int n,x,inc[maxn];
int main() {
int t,i,lt,rt,ans;
scanf("%d",&t);
while(t--){
scanf("%d %d",&n,&x);
for(i = 1; i <= n; i++){
scanf("%lld",sum+i);
sum[i] += sum[i-1];
}
lt = 0;
inc[0] = rt = 1;
ans = n+1;
for(i = 2; i <= n; i++){
while(lt < rt && sum[i] <= sum[inc[rt-1]]) rt--;
inc[rt++] = i;
while(lt + 1 < rt && sum[i] - sum[inc[lt]] >= x){
ans = min(ans,i-inc[lt]);
lt++;
}
}
ans == n+1?puts("-1"):printf("%lld\n",ans);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: