题目连接
http://poj.org/problem?id=2823
Sliding Window
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
线段树,区间最大,最小值。。
1 #include<algorithm> 2 #include<iostream> 3 #include<cstdlib> 4 #include<cstring> 5 #include<cstdio> 6 #define lc root<<1 7 #define rc root<<1|1 8 #define mid ((l+r)>>1) 9 using std::max; 10 using std::min; 11 const int Max_N = 1000010; 12 const int INF = 0x7fffffff; 13 int tmax, tmin, ans1[Max_N], ans2[Max_N]; 14 struct Node { int tmin, tmax; }; 15 struct SegTree { 16 Node seg[Max_N * 3]; 17 inline void push_up(int root) { 18 seg[root].tmax = max(seg[lc].tmax, seg[rc].tmax); 19 seg[root].tmin = min(seg[lc].tmin, seg[rc].tmin); 20 } 21 inline void built(int root, int l, int r) { 22 if (l == r) { 23 scanf("%d", &seg[root].tmax); 24 seg[root].tmin = seg[root].tmax; 25 return; 26 } 27 built(lc, l, mid); 28 built(rc, mid + 1, r); 29 push_up(root); 30 } 31 inline void query(int root, int l, int r, int x, int y) { 32 if (x > r || y < l) return; 33 if (x <= l && y >= r) { 34 tmax = max(tmax, seg[root].tmax); 35 tmin = min(tmin, seg[root].tmin); 36 return; 37 } 38 query(lc, l, mid, x, y); 39 query(rc, mid + 1, r, x, y); 40 } 41 }seg; 42 int main() { 43 #ifdef LOCAL 44 freopen("in.txt", "r", stdin); 45 freopen("out.txt", "w+", stdout); 46 #endif 47 int i, d, n, k; 48 while (~scanf("%d %d", &n, &k)) { 49 d = 0, seg.built(1, 1, n); 50 for (i = 0; i + k <= n; i++) { 51 tmax = -INF, tmin = INF; 52 seg.query(1, 1, n, i + 1, i + k); 53 ans1[d] = tmin, ans2[d++] = tmax; 54 } 55 for (i = 0; i < d; i++) { 56 printf("%d%c", ans1[i], i < d - 1 ? ' ' : ' '); 57 } 58 for (i = 0; i < d; i++) { 59 printf("%d%c", ans2[i], i < d - 1 ? ' ' : ' '); 60 } 61 } 62 return 0; 63 }