[Luogu] P9855 题解

本题可以用双端队列来模拟。

首先定义一个双端队列 a,类型为 char

deque<char> a;

然后把 AE 插入到队列中。

for (char i = 'A'; i <= 'E'; ++i) {
    a.push_back(i);
}

操作 1:

访问队首元素,并插入到队尾,弹出队尾元素。

if (b == 1) {
	while (n--) {
		a.push_back(a.front());
		a.pop_front();
	}
}

操作 2:

与操作 1 同理,把队首和队尾的操作交换一下即可。

if (b == 2) {
	while (n--) {
		a.push_front(a.back());
		a.pop_back();
	}
}

操作 3:

判断 \(n\) 的奇偶性,如果 \(n\) 为偶数,则不需要修改队列,反之若为奇数,只需交换一次前两个元素即可。

if (b == 3) {
	if (n % 2 == 1) {
		x = a.front();
		a.pop_front();
		y = a.front();
		a.pop_front();
		a.push_front(x);
		a.push_front(y);
	}
}

操作 4:

循环输出并结束程序即可。

if (b == 4) {
	for (ll i = 0; i < 5; ++i) {
		cout << a[i] << ' ';
	}
	return 0;
}

整合在一起就有了 AC code:

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

ll b, n;
deque<char> a;
char x, y;

int main() {
    for (char i = 'A'; i <= 'E'; ++i) {
    	a.push_back(i);
	}
	while (cin >> b >> n) {
		if (b == 1) {
			while (n--) {
				a.push_back(a.front());
				a.pop_front();
			}
		}
		if (b == 2) {
			while (n--) {
				a.push_front(a.back());
				a.pop_back();
			}
		}
		if (b == 3) {
			if (n % 2 == 1) {
				x = a.front();
				a.pop_front();
				y = a.front();
				a.pop_front();
				a.push_front(x);
				a.push_front(y);
			}
		}
		if (b == 4) {
			for (ll i = 0; i < 5; ++i) {
				cout << a[i] << ' ';
			}
			return 0;
		}
	}
    return 0;
}
posted @ 2023-11-17 20:54  FurippuWRY  阅读(28)  评论(0)    收藏  举报