【Python基礎程式設計200 ● 檔案的備份】
阿新 • • 發佈:2020-07-25
滑動視窗
Problem:https://ac.nowcoder.com/acm/problem/50528
題解:
單調佇列裸題。
單調佇列維護區間最值,對於單調佇列有兩種操作:
- 插入,新元素從隊尾插入後會破壞佇列中單調性則刪除隊尾元素,知道找到插入後不會破壞單調性的位置為止,再將其插入佇列。
- 獲取最值,讀取隊首元素。
一般情況下,佇列中每個元素儲存兩個值,下標和狀態值。
Code:
/********************************************************** * @Author: Kirito * @Date: 2020-07-26 16:29:46 * @Last Modified by: Kirito * @Last Modified time: 2020-07-26 17:46:42 * @Remark: **********************************************************/ #include <bits/stdc++.h> #define lowbit(x) (x&(-x)) #define CSE(x,y) memset(x,y,sizeof(x)) #define INF 0x3f3f3f3f #define Abs(x) (x>=0?x:(-x)) #define FAST ios::sync_with_stdio(false);cin.tie(0); using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll , ll> pll; const int maxn=1111111; int arr[maxn],n,k; deque<pii> box; int main() { #ifndef ONLINE_JUDGE freopen("in.in","r",stdin); #endif cin>>n>>k; for(int i=0;i<n;i++) cin>>arr[i]; for(int i=0;i<n;i++){ while(!box.empty()&&box.back().second>arr[i]) box.pop_back(); box.push_back(make_pair(i,arr[i])); while(!box.empty()&&box.front().first<i-k+1) box.pop_front(); if(i>=k-1) cout<<box.front().second<<" "; } cout<<endl; while(!box.empty()) box.pop_front(); for(int i=0;i<n;i++){ while(!box.empty()&&box.back().second<arr[i]) box.pop_back(); box.push_back(make_pair(i,arr[i])); while(!box.empty()&&box.front().first<i-k+1) box.pop_front(); if(i>=k-1) cout<<box.front().second<<" "; } cout<<endl; return 0; }