【题目来源】
https://www.acwing.com/problem/content/description/136/
【题目描述】
达达现在碰到了一个棘手的问题,有 N 个整数需要排序。
达达手头能用的工具就是若干个双端队列。
她从 1 到 N 需要依次处理这 N 个数,对于每个数,达达能做以下两件事:
1. 新建一个双端队列,并将当前数作为这个队列中的唯一的数;
2. 将当前数放入已有的队列的头之前或者尾之后。
对所有的数处理完成之后,达达将这些队列按一定的顺序连接起来后就可以得到一个非降的序列。
请你求出最少需要多少个双端序列。
【输入格式】
第一行输入整数 N,代表整数的个数。
接下来 N 行,每行包括一个整数 Di,代表所需处理的整数。
【输出格式】
输出一个整数,代表最少需要的双端队列数。
【数据范围】
1≤N≤200000
【输入样例】
6
3
6
0
9
6
3
【输出样例】
2
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int N=2e5+5;
typedef pair<int,int> PII;
PII a[N];
int n;
int main() {
cin>>n;
for(int i=0; i<n; i++) {
cin>>a[i].first;
a[i].second=i;
}
sort(a,a+n);
int i=0,last=n+1,ans=1;
int dir=-1; //dir is used to record directions
while(i<n) {
int j=i+1;
while(j<n && a[j].first==a[i].first) {
j++;
}
int minx=a[i].second;
int maxx=a[j-1].second;
if(dir==-1) { //dir=-1 indicates decline
if(last>maxx) last=minx;
else {
dir=1; //dir=1 indicates increase
last=maxx;
}
} else {
if(last<minx) last=maxx;
else {
ans++;
last=minx;
dir=-1;
}
}
i=j;
}
cout<<ans<<endl;
return 0;
}
/*
in:
6
3
6
0
9
6
3
out:
2
*/
【参考文献】
https://www.cnblogs.com/Horb7/p/15603051.html
https://www.acwing.com/solution/acwing/content/7210/
https://www.acwing.com/solution/content/27971/