标签:
| Time Limit: 12000MS | Memory Limit: 65536K | |
| Total Submissions: 54931 | Accepted: 15815 | |
| Case Time Limit: 5000MS | ||
Description
| 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
Output
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
Source
#include <cstdio>
#include <utility>
using namespace std;
const int MAXN = 1e6+5;
int n, k;
int a[MAXN];
pair<int, int> q[MAXN];
int res_min[MAXN], res_max[MAXN];
void get_min()
{
int l = 0, r = 0;
int i;
for(i = 0; i < k-1; ++i){
while(l < r && a[i] <= q[r-1].first)
--r;
q[r].first = a[i];
q[r++].second = i;
}
int cnt = 0;
for(; i < n; ++i){
while(l < r && a[i] <= q[r-1].first)
--r;
q[r].first = a[i];
q[r++].second = i;
while(q[l].second < i-k+1)
++l;
res_min[cnt++] = q[l].first;
}
for(i = 0; i < cnt-1; ++i)
printf("%d ", res_min[i]);
printf("%d\n", res_min[cnt-1]);
}
void get_max()
{
int l = 0, r = 0;
int i;
for(i = 0; i < k-1; ++i){
while(l < r && a[i] >= q[r-1].first)
--r;
q[r].first = a[i];
q[r++].second = i;
}
int cnt = 0;
for(; i < n; ++i){
while(l < r && a[i] >= q[r-1].first)
--r;
q[r].first = a[i];
q[r++].second = i;
while(q[l].second < i-k+1)
++l;
res_max[cnt++] = q[l].first;
}
for(i = 0; i < cnt-1; ++i)
printf("%d ", res_max[i]);
printf("%d\n", res_max[cnt-1]);
}
void solve()
{
get_min();
get_max();
}
int main()
{
scanf("%d%d", &n, &k);
for(int i = 0; i < n; ++i)
scanf("%d", &a[i]);
solve();
return 0;
}
标签:
原文地址:http://www.cnblogs.com/inmoonlight/p/5851072.html