当前位置: 代码迷 >> 综合 >> POJ 2823(单调队列模板)
  详细解决方案

POJ 2823(单调队列模板)

热度:3   发布时间:2024-02-21 20:38:24.0

区间最大值最小值 

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#include <bitset>
using namespace std;
#define IO                       \ios::sync_with_stdio(false); \// cin.tie(0);                  \// cout.tie(0);
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
typedef unsigned long long ULL;
typedef long long LL;
const int maxn = 1e6 + 100;
int n, k;
int a[maxn], pos[maxn], que[maxn], MAX[maxn], MIN[maxn];
void Get_Max()
{int head = 1, tail = 0;for (int i = 1; i <= n; i++){while (head <= tail && que[tail] <= a[i])--tail;que[++tail] = a[i];pos[tail] = i;if (i < k)continue;while (pos[head] < i - k + 1)head++;MAX[i - k + 1] = que[head];if (i >= k)printf("%d ", que[head]);}
}
void Get_Min()
{int head = 1, tail = 0;for (int i = 1; i <= n; i++){while (head <= tail && que[tail] >= a[i])--tail;que[++tail] = a[i];pos[tail] = i;if (i < k)continue;while (pos[head] < i - k + 1)head++;MIN[i - k + 1] = que[head];if (i >= k)printf("%d ", que[head]);if (i == n)printf("\n");}
}
int main()
{cin >> n >> k;for (int i = 1; i <= n; i++)scanf("%d", &a[i]);Get_Min();Get_Max();return 0;
}