Code-Animal

该代码定义了一个AnimalShell类,使用两个队列管理猫和狗的入队和出队操作。enqueue方法根据类型将动物编号放入相应队列,dequeueAny和dequeueDog、dequeueCat方法处理出队请求。renewShell方法确保当前处理的队列非空。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;

class AnimalShell
{
protected:
	queue<int> curShell;
	queue<int> animalNumber[2];
public:
	void renewShell();
	void enqueue(int number, string type);
	void dequeueAny(int* number, string* type);
	int dequeueDog();
	int dequeueCat();
};
void AnimalShell::renewShell()
{
	if (!curShell.empty())
	{
		while (animalNumber[curShell.front()].empty())
		{
			if (animalNumber[curShell.front()].empty())
				curShell.pop();
			if (curShell.empty())
				return ;
		}
	}
}

void AnimalShell::enqueue(int number, string type)
{
	if (curShell.empty())
	{
		if (type == "cat")
			curShell.push(0);
		else
			curShell.push(1);
	}
	else if (curShell.size() == 1)
	{
		if (type == "cat" && curShell.front() != 0)
			curShell.push(0);
		else if (type == "dog" && curShell.front() != 1)
			curShell.push(1);
	}
	if (type == "cat")
		animalNumber[0].push(number);
	else
		animalNumber[1].push(number);
}

void AnimalShell::dequeueAny(int* number, string* type)
{
	if (curShell.empty())
	{
		*number = -1;
		*type = "none";
	}
	else
	{
		if (curShell.front() == 0)
		{
			*number = dequeueCat();
			*type = "cat";
		}
		else
		{
			*number = dequeueDog();
			*type = "dog";
		}
	}
}

int AnimalShell::dequeueDog()
{
	renewShell();

	if (animalNumber[1].empty())
		return -1;
	else
	{
		int temp = animalNumber[1].front();
		animalNumber[1].pop();

		if (animalNumber[curShell.front()].empty())
			curShell.pop();
		return temp;
	}
}

int AnimalShell::dequeueCat()
{
	renewShell();

	if (animalNumber[0].empty())
		return -1;
	else
	{
		int temp = animalNumber[0].front();
		animalNumber[0].pop();

		if (animalNumber[curShell.front()].empty())
			curShell.pop();
		return temp;
	}
}

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		AnimalShell shell;

		int n;
		cin >> n;
		while (n--)
		{
			int number = 0;
			string operate,type;
			cin >> operate;

			if (operate == "enqueue")
			{
				cin >> number >> type;
				shell.enqueue(number, type);
			}
			else
			{
				if (operate == "dequeueAny")
					shell.dequeueAny(&number, &type);
				else if (operate == "dequeueCat")
				{
					number = shell.dequeueCat();
					if (number != -1)
						type = "cat";
					else
						type = "none";
				}
				else if (operate == "dequeueDog")
				{
					number = shell.dequeueDog();
					if (number != -1)
						type = "dog";
					else
						type = "none";
				}
				cout << '[' << number << ' ' << type << "] ";
			}
		}
		cout << endl;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值