UVA 12697 Minimal Subarray Length
2014-08-23 16:03
656 查看
Minimal Subarray Length
Time Limit: 3000msMemory 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
相关文章推荐
- UVALive_6609_Minimal Subarray Length(RMQ+二分)
- UVALive 6609(Minimal Subarray Length)维护递增序列|RMQ
- uvalive 6609 - Minimal Subarray Length(离散化+树状数组)
- UVALive 6609 Minimal Subarray Length(最大子段)
- UVALive 6609 Minimal Subarray Length (查找+构建排序数组)
- [J - Minimal Subarray Length UVALive - 6609] 区间问题
- 【单调栈思路】Minimal Subarray Length UVALive - 6609
- Uva 6609 - Minimal Subarray Length(RMQ)
- UVALive 6609 Minimal Subarray Length rmq+二分or单调队列
- UVALive 6609 Minimal Subarray Length (查找+构建排序数组)
- HOJ 13006 Minimal Subarray Length (单调队列或RMQ加二分)
- Minimal Subarray Length
- Minimal Subarray Length
- Minimal Subarray Length
- Minimal Subarray Length
- Minimal Subarray Length
- LA 6609 - Minimal Subarray Length
- Minimal Subarray Length
- Minimal Subarray Length
- LeetCode:Maximum Length of Repeated Subarray