其他分享
首页 > 其他分享> > AcWing 2022.7.20

AcWing 2022.7.20

作者:互联网

链表模拟 + 队列模拟

可以用队列模拟,维护未弹出的数据和顺序。
也可以直接按题目要求维护循环队列,只需要单链表就够了。

队列:

#include <bits/stdc++.h>
using namespace std;

const int N = 60;

int T;
int n;
int ne[N];

int main() {
	cin >> T;
	while (T--) {
		cin >> n;

		queue<int> q;

		for (int i = 1; i <= n; i++)
			q.push(i);

		int cnt = 1;
		while (!q.empty()) {
			if (cnt == 3) {
				int t = q.front();
				q.pop();
				cnt = 1;
				cout << t << " ";
			} else {
				int t = q.front();
				q.pop();
				q.push(t);
				cnt++;
			}
		}
		cout << endl;

	}

	return 0;
}

循环链表:

#include <bits/stdc++.h>
using namespace std;

const int N = 60;

int T;
int n;
int ne[N];

int main() {
	cin >> T;
	while (T--) {
		cin >> n;
		for (int i = 1; i < n; i++)
			ne[i] = i + 1;
		ne[n] = 1;
		int cnt = 1;
		int dex = 1;
		while (ne[dex] != dex) {
			if (cnt == 2) {
				cout << ne[dex]	<< " ";
				ne[dex] = ne[ne[dex]];
				cnt = 1;
			} else
				cnt++;
			dex = ne[dex];
		}
		cout << ne[dex] << endl;
	}

	return 0;
}

标签:dex,20,int,ne,cin,队列,while,2022.7,AcWing
来源: https://www.cnblogs.com/superPG/p/16498037.html