1. 程式人生 > >【模板】deque實現單調隊列

【模板】deque實現單調隊列

getch info 常數 單調隊列 har nbsp lse esp gin

雙端隊列deque容器:

關於deque最常用的有這幾個函數

技術分享圖片

都是成員函數

雙端隊列模板題:【洛谷】P2952 [USACO09OPEN]牛線Cow Line

技術分享圖片
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<deque>
 6 using namespace std;
 7 
 8 int n, cnt;
 9 deque<int> q;
10 11 int main() { 12 scanf("%d\n", &n); 13 char s[21]; 14 for(int i=1; i<=n; ++i) { 15 gets(s); 16 if(s[0] == A) 17 if(s[2] == L) q.push_front(++cnt); 18 else q.push_back(++cnt); 19 if(s[0] == D) { 20 int m = 0
, j = 1; 21 while(s[j]<0 || s[j]>9) ++j; 22 while(s[j]>=0 && s[j]<=9) 23 m = (m << 3) + (m << 1) + s[j] - 48, ++j; 24 while(m--) { 25 if(s[2] == L) q.pop_front(); 26 else
q.pop_back(); 27 } 28 } 29 30 } 31 deque<int>::iterator it; 32 for(it=q.begin(); it!=q.end(); ++it) 33 printf("%d\n", *it); 34 }
P2952 [USACO09OPEN]牛線Cow Line

單調隊列deque容器實現:

設一個數組a,可以修改某一個元素的值,求a中所有元素的最小(大)值

每次從頭掃到尾的時間復雜度O(n2)太高了,st表雖然是O(1)查詢但不支持修改

可以使用線段樹O(n log2 n)來做但復雜度還是不夠優秀,常數還大

單調隊列登場了:

每次加入雙端隊列尾一個元素num時,從隊尾將隊列中所有比num大的元素都pop出去,再push_back(num)

這樣就能實現單調隊列了。

單調隊列模板題:【洛谷】P1440 求m區間內的最小值

技術分享圖片
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<deque>
 5 using namespace std;
 6 
 7 const int MAXN = 2000000 + 1;
 8 
 9 int n, m;
10 int a[MAXN];
11 deque<int> q;
12 
13 inline int read() {
14     int x=0, f=1; char ch=getchar();
15     while(ch<0 || ch>9) {
16         if(ch == -) f = -1;
17         ch = getchar();
18     }
19     while(ch>=0 && ch<=9)
20         x=(x<<3)+(x<<1)+ch-48, ch=getchar();
21     return x * f;
22 }
23 
24 int main() {
25     n = read(), m = read();
26     for(int i=1; i<=n; ++i) a[i] = read();
27     puts("0");
28     for(int i=1; i<n; ++i) {
29         if(i>m && q.front()==a[i-m]) q.pop_front();
30         while(!q.empty() && q.back()>a[i]) q.pop_back();
31         q.push_back(a[i]);
32         printf("%d\n", q.front());
33     }
34 }
P1440 求m區間內的最小值

【模板】deque實現單調隊列