POJ 2823 Sliding Window
Time Limit: 12000MS | Memory Limit: 65536K | |
Total Submissions: 43129 | Accepted: 12740 | |
Case Time Limit: 5000MS |
Description
An array of size n ≤ 106 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example:
The array is [1 3 -1 -3 5 3 6 7], and k is 3.
The array is [1 3 -1 -3 5 3 6 7], and k is 3.
Window position | Minimum value | Maximum value |
---|---|---|
[1 3 -1] -3 5 3 6 7 | -1 | 3 |
1 [3 -1 -3] 5 3 6 7 | -3 | 3 |
1 3 [-1 -3 5] 3 6 7 | -3 | 5 |
1 3 -1 [-3 5 3] 6 7 | -3 | 5 |
1 3 -1 -3 [5 3 6] 7 | 3 | 6 |
1 3 -1 -3 5 [3 6 7] | 3 | 7 |
Your task is to determine the maximum and minimum values in the sliding window at each position.
Input
The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line.
Output
There
are two lines in the output. The first line gives the minimum values in
the window at each position, from left to right, respectively. The
second line gives the maximum values.
Sample Input
8 3
1 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 3
3 3 5 5 6 7
题解:打了个线段树,维护区间最大最小值,时间复杂度是O((n - k + 1)·logn);大约六秒半跑过。。友情提示:求区间最大最小时一起求。。。。不然复杂度*常数2,T成狗。。估计也就我这样的才分开求。。
另外,网上的题解说的是O(n)的单调队列,表示现在还并不会。。(这人太弱了吧。。这都不会。。)
CODE:
#include <cstdio> #define REP(i, s, n) for(int i = s; i <= n; i ++) #define REP_(i, s, n) for(int i = n; i >= s; i --) #define max(a, b) a > b ? a : b #define min(a, b) a < b ? a : b #define MAX_N 1000000 + 10 int n, k, data[MAX_N]; struct node{ int l, r, mx, mn; }a[MAX_N << 4]; void updata(int i){ int t1 = i << 1, t2 = t1 + 1; a[i].mx = max(a[t1].mx, a[t2].mx); a[i].mn = min(a[t1].mn, a[t2].mn); } void maketree(int i, int l, int r){ a[i].l = l; a[i].r = r; if(a[i].l == a[i].r){ a[i].mx = a[i].mn = data[l]; return; } int mid = (a[i].l + a[i].r) >> 1, t1 = i << 1, t2 = t1 + 1; maketree(t1, l, mid); maketree(t2, mid + 1, r); updata(i); } int mi, ma; void Query(int i, int l, int r){ if(a[i].l >= l && a[i].r <= r){ mi=min(mi,a[i].mn); ma=max(ma,a[i].mx); return; } if(a[i].l == a[i].r) return; int mid = (a[i].l + a[i].r) >> 1, t1 = i << 1, t2 = t1 + 1; if(r <= mid) Query(t1, l, r); else if(l > mid) Query(t2, l, r); else Query(t1, l, mid), Query(t2, mid + 1, r); } int res_max[MAX_N], res_min[MAX_N]; int main(){ scanf("%d%d", &n, &k); REP(i, 1, n) scanf("%d", &data[i]); maketree(1, 1, n); if(k >= n){ mi = 99999999, ma = -99999999; Query(1, 1, n); printf("%d\n%d\n", mi, ma); } else{ REP(i, 1, n - k + 1){ mi = 99999999, ma = -99999999; Query(1, i, i + k - 1); res_max[i] = ma, res_min[i] = mi; } REP(i, 1, n - k + 1) printf("%d ", res_min[i]); printf("\n"); REP(i, 1, n - k + 1) printf("%d ", res_max[i]); printf("\n"); } return 0; }