队列的四道习题

练习了几道新学的队列有关的几道习题,以下是题目加代码:

第一题如下图:

对于此题由于有n个队列所以我们可以考虑引入front和rear数组来代表不同队列的队首和队尾,并用memset函数将他们赋初始值,然后再从一到m进行枚举并对对应操作进行代码抒写。

以下是代码实现: 

#include<iostream>
#include<cstring>
using namespace std;
int n,m;
int q[101][1001];
int front[101],rear[101];
int main(){
	cin>>n>>m;
	 memset(front, 0, sizeof(front)); // 初始化 front 数组
    memset(rear, -1, sizeof(rear));  // 初始化 rear 数组
	for(int i=1;i<=m;i++){
		int id,opt;
		cin>>id>>opt;
		if(opt==1){
			int x;
			cin>>x;
			q[id][++rear[id]]=x;
		}
		else {
			if(front[id]<=rear[id])
			{cout<<q[id][front[id]]<<endl;
			++front[id];}
		    else cout<<"error"<<endl;
		}
	}
	return 0;
}

接下来再看一道题目:

 

以下是代码实现: 

#include<iostream>
#include<cstring>
using namespace std;
int n,q[101][3],front=1,rear=0;
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		int opt;
		cin>>opt;
		if(opt==1){
			int x,y;
			cin>>x>>y;
			++rear;
			q[rear][1]=x;
			q[rear][2]=y;
		}
		else {
			if(front<=rear){
				cout<<q[front][1]<<' '<<q[front][2]<<endl;
				++front;
			}
			else cout<<"error"<<endl;
		}
	}
	return 0;
}

再看一道题目:

 首先是我的代码:

#include<iostream>
using namespace std;
int n,front=1,rear=0,q[101];
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		int opt,x;
		cin>>opt>>x; 
		if(opt==1) q[++rear]=x;
		else {
			int ans=0;
			while(1)
			{
				 if(front>rear)  {
				 cout<<ans<<endl;
				 break;}
			else if(q[front]!=x) {++ans,++front;}
			else {
			++ans;
			++front;
			cout<<ans<<endl;
			break;} 
	        }
		}
	}
	return 0;
}

再来看看标准的更美观的代码:

#include<iostream>
using namespace std;
int n,q[101],front=1,rear=0;
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		int opt,x;
		cin>>opt>>x;
		if(opt==1)
		q[++rear]=x;
		else {
			int tot=0;
			while(rear>=front){
				int y=q[front];
				++front;
				++tot;
				if(x==y)
				break;
			}
			cout<<tot<<endl;
		}
	}
	return 0;
}

这里的第二段标准代码就比我第一段少了一些码量同时思路能更为清晰的感知到,看起来更加美观,值得我这种初学者去学习。

来看最后一道题目:

 这道题是不是非常有趣?他每次出列一个人之后又要重新更新队首所以很值得我们去思考这道问题的处理方式,以下是代码实现,不妨仔细理解:

#include<iostream>
using namespace std;
int n,m,q[10001],front=1,rear;
int main(){
	cin>>n>>m;
	rear=n;
	for(int i=1;i<=n;i++)
		q[i]=i;
		int x=0;
		while(rear>=front){
			int y=q[front];
			++front;
			++x;
			if(x==m){
			cout<<y<<' ';
		    x=0;}
			else{
			q[++rear]=y;	
			} 
		}
		return 0;
}

我用我自己的理解对这段代码做出解释:

首先我们存入总人数和要报的数字,并引入一个数组q代表每个人的编号,然后让x来代表每次每个人报的数字是多少,当队列不为空的时候,我们让y来替代此时准备报数的人,然后更新队首和x,x就是y要报的数字,如果x和m相等那么这个人就需要出队,并输出他的编号,并将x重新初始化,否则就继续报下去,于是这个人不可以出队,将他更新在这时候的队伍尾部。

精髓就是将一个报了数不出队的人放在了队伍尾部,解决了这个题围成一个圈的题干的问题,而把他看成一条可以不断更新的直线队列。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

残念亦需沉淀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值