洛谷 - P2032 扫描 (单调队列)

题目传送
洛谷 - P2032 扫描 (单调队列)_第1张图片
洛谷 - P2032 扫描 (单调队列)_第2张图片
思路:
单调队列模板题没有什么好解释的,就是再熟悉下模板
就是在k区间内维护数组的单调性

AC代码

#include 
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 5e3 + 10;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const int mod = 1e9+7;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
struct node
{
    int ans;
    int val;
};
signed main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    //    freopen("input.txt","r",stdin);
    //    freopen("output.txt","w",stdout);
    deque<node> q;
    int n,k;
    cin >> n >> k;
    for(int i = 1,num;i <= n;i++)
    {
        cin >> num;
        while(!q.empty() && num > q.back().val)
            q.pop_back();
        q.push_back({i,num});
        while(!q.empty() && i - q.front().ans >= k)
            q.pop_front();
        if(i >= k)
            cout << q.front().val << endl;
    }
}

你可能感兴趣的:(洛谷)