stack queue
知识点
试管
例题1![在这里插入图片描述](https://img-blog.csdnimg.cn/46e04030447f44eb8a4749f5b2b4dfcb.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAbWluZ3l1MTk=,size_20,color_FFFFFF,t_70,g_se,x_16)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
stack<int> q;
int a[N];
int main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i ++ )
cin >> a[i];
int j = 1;
for(int i = 1; i <= n; i ++ )
{
q.push(i);
while(q.size() && a[j] == q.top())
{
q.pop();
j ++ ;
}
}
if(!q.empty()) cout << "YES" << endl;
else cout << "NO" << endl;
}
一个 stack 告诉动态的stack排序什么时候开始删除元素
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
stack<int> a;
stack<int> q;
signed main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i ++ )
{
int x;
cin >> x;
a.push(x);
}
int j = 1;
for(int i = 1; i <= n; i ++ )
{
q.push(i);
while(q.size() && a.top() == q.top())
{
q.pop();
a.pop();
}
}
if(!q.empty()) cout << "NO" <<endl;
else cout << "YES" << endl;
return 0;
}
例题2
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n;
int maxn[N];
int a[N];
stack<int> q;
int main()
{
cin >> n;
for(int i = 1; i <= n; i ++ )
cin >> a[i];
for(int i = n; i ; i -- )
maxn[i] = max(a[i], maxn[i + 1]);
for(int i = 1; i <= n; i ++ )
{
q.push(a[i]);
while(!q.empty() && q.top() > maxn[i + 1])
{
printf("%d ", q.top());
q.pop();
}
}
return 0;
}
数组手动实现
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n;
int a[N];
int maxn[N];
int q[N];
int main()
{
cin >> n;
for(int i = 1; i <= n; i ++ ) cin >> a[i];
// yu chu li
for(int j = n; j ; j -- ) maxn[j] = max(a[j], maxn[j + 1]);
int top = 0;
for(int i = 1; i <= n; i ++ )
{
q[++ top] = a[i];
while(top > -1 && q[top] > maxn[i + 1])
{
printf("%d ", q[top]);
top -- ;
}
}
}
[NOIP2004]合并果子
注意 q里面也有可能空
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int n;
int a[N];
queue<int> q, q2;
int main()
{
cin >> n;
for(int i = 1; i <= n; i ++ ) cin >> a[i];
sort(a + 1, a + n + 1);
for(int i = 1; i <= n; i ++ ) q.push(a[i]);
long long ans = 0;
for(int i = 1; i < n; i ++ )
{
int x[3];
for(int j = 1; j <= 2; j ++ )
{
if(q2.empty() || !q.empty() && q.front() < q2.front()) // 注意要判断q.empty();
{
x[j] = q.front();
q.pop();
}
else
{
x[j] = q2.front();
q2.pop();
}
}
ans += x[1] + x[2];
q2.push(x[1] + x[2]);
}
cout << ans ;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
vector<int> q;
int main()
{
int n, m;
cin >>n >>m;
while(m -- )
{
int a, b;
cin >> a;
if(a == 1) cin >> b, q.insert(q.begin(), b);
else if(a == 2) q.erase(q.begin());
else if(a == 3) cin >> b, q.push_back(b);
else if(a == 4) q.pop_back();
else if(a == 5) reverse(q.begin(), q.end());
else if(a == 6)
{
cout << q.size() << endl;
for(int i = 0; i < q.size(); i ++ )
cout << q[i] << ' ';
cout << endl;
}
else sort(q.begin(), q.end());
}
}