单调栈、单调队列

单调栈

AcWing 830

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<bits/stdc++.h>
using namespace std;

const int N = 100010;

int n;
int stk[N], tt;

int main(int argc, char const *argv[])
{
//ios::sync_with-stdio(false),cin.tie(0),cout.tie(0);//也可
scanf("%d", &n);//输入输出数据较大,使用C库函数

for (int i = 0; i < n; i ++){
int x;
scanf("%d", &x);
/*单调栈,找寻数字左边比它小的最近的数*/
while (tt && stk[tt] >= x ) tt --; // 维护单调栈
if (tt) printf("%d ", stk[tt]);
else printf("-1 ");

stk[ ++ tt] = x; // 补充单调栈
}

return 0;
}

单调队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*单调队列,可求滑动窗口的**最大值、最小值**、二分找值,多重背包*/

#include<bits/stdc++.h>

using namespace std;

const int N = 100010;

int n, k;
int a[N], q[N];

int main(int argc, char const *argv[])
{
scanf("%d", &n);//输入输出数据较大,使用C库函数
//ios::sync_with-stdio(false),cin.tie(0),cout.tie(0);

for (int i = 0; i < n; i ++) scanf("%d", &a[i]);

/* 最小值 */
int hh = 0, tt = -1;
for (int i = 0; i < n; i ++){
//判断队头是否已经滑出窗口
if (hh <= tt && i - k + 1 > q[hh]) hh ++ ;
while(hh <= tt && a[q[tt]] >= a[i]) tt -- ;
q[ ++ tt] = i;
if(i >= k - 1) printf("%d ", a[q[hh]]);
}

puts("");

/* 最大值 */
int hh = 0, tt = -1;
for (int i = 0; i < n; i ++){
//判断队头是否已经滑出窗口
if (hh <= tt && i - k + 1 > q[hh]) hh ++ ;
while(hh <= tt && a[q[tt]] <= a[i]) tt -- ;
q[ ++ tt] = i;
if(i >= k - 1) printf("%d ", a[q[hh]]);
}

puts("");

return 0;
}

洛谷P1886题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <bits/stdc++.h>

using namespace std;

const int N = 1000006;

int a[N];

deque<int>q;

int main(){
int n, m; cin >> n >> m;
for (int i = 1; i <= n; ++i)
{
cin >> a[i];
}
for (int i = 1; i <= n; ++i)
{
while(!q.empty() && a[q.back()] > a[i]) q.pop_back();
q.push_back(i);
if (i >= m){
q.push_back(i);
while (!q.empty() && q.front() <= i - m) q.pop_front();
printf("%d ", a[q.front()]);
}
}
printf("\n");
while (!q.empty()) q.pop_front();
for (int i = 1; i <= n; ++i)
{
while(!q.empty() && a[q.back()] < a[i]) q.pop_back();
q.push_back(i);
if (i >= m){
q.push_back(i);
while (!q.empty() && q.front() <= i - m) q.pop_front();
printf("%d ", a[q.front()]);
}
}
//printf("\n");
return 0;
}

HDU 1003

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <bits/stdc++.h>

using namespace std;

const int INF = 0x7fffffff;

int main(){
int t; cin >> t;
for (int i = 1; i <= t; ++i)
{
int n; cin >> n;
int maxsum = -INF;
int start = 1, end = 1, p = 1;
int sum = 0;
for (int j = 1; j <= n; ++j)
{
int a; cin >> a; sum += a;
if (sum > maxsum){maxsum = sum; start = p; end = j;}
if (sum < 0){
sum = 0;
p = j + 1;
}
}
printf("Case %d:\n", i);printf("%d %d %d\n", maxsum,start,end);
if(i != t)cout << endl;
}
return 0;
}