1.基本操作
#include<iostream>
#include <stack>
#include<queue>
using namespace std;
queue<int> q;
stack<int> stk;
void text01(){
stk.push(1);stk.push(2);stk.push(3);stk.push(4);
q.push(5);q.push(6);q.push(7);q.push(8);
cout<<"栈输出:"<<endl;
while(!stk.empty()){//输出一个删一个
cout<<stk.top()<<" ";
stk.pop();
}
cout<<endl;
while(!q.empty()){//输出一个删一个
cout<<q.front()<<" ";
q.pop();
}
}
int main() {
text01();
return 0;
}
2.应用
模拟环的方式都右哪些?
线性扩增2倍模拟环
数组的循环位移
线性队列模拟环
因为队列是头删尾插,通过把pop的数据用临时变量接收,然后再立马push,就可以达到环的效果
3.习题
1332:【例2-1】周末舞会
#include<iostream>
#include <stack>
#include<queue>
using namespace std;
queue<int> man,woman;
int n1,n2,song;
void text01(){
cin>>n1>>n2>>song;
for(int i=1;i<=n1;i++){
man.push(i);
}
for(int i=1;i<=n2;i++){
woman.push(i);
}
for(int i=1;i<=song;i++){
int x1=man.front();
int x2=woman.front();
man.pop();woman.pop();
cout<<x1<<" "<<x2<<endl;
man.push(x1);woman.push(x2);
}
}
int main() {
text01();
return 0;
}
1334:【例2-3】围圈报数
#include<iostream>
#include <stack>
#include<queue>
using namespace std;
queue<int> q;
int n,m,k=1;
void text01(){
cin>>n>>m;
for(int i=1;i<=n;i++){
q.push(i);
}
while(q.size()!=1){
if(k!=m){
int x=q.front();
q.pop();
q.push(x);
k++;
}
else{
k=1;
cout<<q.front()<<" ";
q.pop();
}
}
cout<<q.front();
}
int main() {
text01();
return 0;
}
P1540 [NOIP2010 提高组] 机器翻译
#include<iostream>
#include <stack>
#include<queue>
using namespace std;
queue<int> q;
const int N=1e3+10;
int a[N],m,n,cnt;
bool vis[N];
void text01(){
cin>>m>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
if(!vis[a[i]]){
if(q.size()==m){
vis[q.front()]=false;
q.pop();
}
q.push(a[i]);
vis[a[i]]=true;
cnt++;
}
}
cout<<cnt<<endl;
}
int main() {
text01();
return 0;
}
1333:【例2-2】Blah数集
#include<iostream>
#include <stack>
#include<queue>
using namespace std;
const int N=1e6+10;
int a1,n1;
void Blah_Solution(int a,int n){
int k=1;
queue<int> q1,q2;
q1.push(2*a+1);
q2.push(3*a+1);
int x;
while(k!=n){
if(q1.front()<q2.front()){
x=q1.front();
q1.pop();
}
else if(q1.front()==q2.front()){
x=q1.front();
q1.pop();
q2.pop();
}
else{
x=q2.front();
q2.pop();
}
k++;
q1.push(2*x+1);
q2.push(3*x+1);
}
cout<<x<<endl;
}
void text01(){
while(cin>>a1>>n1){
Blah_Solution(a1,n1);
}
}
int main() {
text01();
return 0;
}