http://poj.org/problem?id=2823
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.
8 3 1 3 -1 -3 5 3 6 7
-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 ? ' ' : '\n'); 57 } 58 for (i = 0; i < d; i++) { 59 printf("%d%c", ans2[i], i < d - 1 ? ' ' : '\n'); 60 } 61 } 62 return 0; 63 }