南园十三首·其五

男儿何不带吴钩,收取灯塔五十州。

沙场秋点兵:

刘成将军正在排兵布阵,他要将若干个士兵拍成一排,每个士兵都有一个战斗值x,不同士兵的战斗值可能相同。

假设初始时,队伍为空,但是队伍的正方向朝东(若队伍中有士兵,则他们面朝东,即东边是队伍队首,西边是队伍队尾)

刘成将军会发布以下三条命令:

命令一名士兵从队尾插入队伍

命令一名士兵从队首离开队伍(若队伍里面没有士兵,则忽略此操作)

命令队伍向后转(队伍的正方向改变,队首变为队尾,队尾变为队首。)

输入格式:

第一行一个正整数q(1<=q<=400000),表示命令的数量

接下来q行,

若是 1 x,则将一个战斗值为x的士兵从队尾插入队伍(1<=x<=1000000)。

若是 2,则命令一名士兵从队首离开队伍(若当前队伍中没有士兵,则忽略此操作)

若是 3,则命令队伍向后转

输出格式:

对于每个输入输出一行一个整数,为当前队首和队尾两名士兵的战斗值的异或值(这里的异或是按位异或,运算符为 '^')。

若当前队伍为空,则输出-1

输入样例1:

5
1 2
1 3
3
2
2

输出样例1:

0
1
1
0
-1

输入样例2:

4
1 2
3
1 3
3

输出样例2:

0
0
1
1

 思路:采用队列,因为队头队尾会互换,设置一个正序标志,逆序的队列操作和正序的队列差不多,注意输出采用异或运算符。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct Queue {
	int flag;//正序则为0,逆序为1
	int front;
	int rear;
	int* base;
	int Max;//队列长度
}Queue;
//除了初始化队列,其他所有操作都要考虑正序逆序
void IniQueue(Queue& Q, int n);
void EnQueue(Queue& Q, int x);
int DeQueue(Queue& Q);
void ChangeQueue(Queue& Q, int j);
int IfQueue(Queue Q);
int main() {
	int n, i, x, b, j = 0;
	scanf("%d", &n);
	Queue Q;
	IniQueue(Q, n);
	for (i = 0; i < n; ++i)
	{
		scanf("%d", &b);
		if (b == 1)
		{
			scanf("%d", &x);
			EnQueue(Q, x);
			printf("%d\n", IfQueue(Q));
		}
		else if (b == 2)
		{
			if (DeQueue(Q))
			{
				printf("%d\n",IfQueue(Q));
			}
			else
				printf("-1\n");
		}
		else
		{
			j++;
			ChangeQueue(Q, j);
			printf("%d\n", IfQueue(Q));
		}
	}
	return 0;
}

void IniQueue(Queue& Q, int n)
{
	Q.base = (int*)malloc((n + 1) * sizeof(int));//多一个位置用来判断队满
	Q.front = 0;
	Q.rear = 0;
	Q.Max = (n + 1);
	Q.flag = 0;
}
void EnQueue(Queue& Q, int x)
{
	if (Q.flag == 0)//正序标志
	{
		Q.base[Q.rear] = x;
		Q.rear = (Q.rear + 1 + Q.Max) % Q.Max;
	}
	else {//逆序标志
		Q.base[Q.rear] = x;
		Q.rear = (Q.rear - 1 + Q.Max) % Q.Max;
	}
}
int DeQueue(Queue& Q)
{
	if (Q.front == Q.rear)
		return 0;
	if (Q.flag == 0)
		Q.front = (Q.front + 1 + Q.Max) % Q.Max;
	else
		Q.front = (Q.front - 1 + Q.Max) % Q.Max;
	return 1;
}
void ChangeQueue(Queue& Q, int j)
{
	int z;
	if(Q.flag==0)
	{
		z = (Q.front - 1 + Q.Max) % Q.Max;
		Q.front = (Q.rear - 1 + Q.Max) % Q.Max;
		Q.rear = z;
	}
	else
	{
		z = (Q.front + 1 + Q.Max) % Q.Max;
		Q.front = (Q.rear + 1 + Q.Max) % Q.Max;
		Q.rear = z;
	}
	Q.flag = j % 2;
}
int IfQueue(Queue Q)
{
	if (Q.rear == Q.front)
		return -1;
	if (Q.flag == 0)
	{
		return (Q.base[Q.front]) ^ (Q.base[(Q.rear - 1 + Q.Max) % Q.Max]);
	}
	else
	{
		return (Q.base[Q.front]) ^ (Q.base[(Q.rear + 1 + Q.Max) % Q.Max]);
	}
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值