CF792B Counting-out Rhyme 的题解

这篇文章介绍了如何运用C++编程语言,特别是队列数据结构,来解决一个类似于约瑟夫问题的儿童游戏。在游戏过程中,孩子们按顺时针编号并按特定规则淘汰,代码示例展示了如何利用队列进行模拟和优化,避免过度循环导致超时。

CF792B Counting-out Rhyme 的题解

洛谷传送门
CF传送门

题目大意

n n n 个孩子在玩一个游戏。 孩子们站成一圈,按照顺时针顺序分别被标号为 1 1 1 n n n

开始游戏时,第一个孩子成为领导。 游戏进行 k k k 轮。 在第 i i i 轮中,领导会从他顺时针方向下一个孩子开始数 a i a_i ai 个孩子。

最后数到的那个孩子出局,再下一个孩子成为新的领导。

前置知识

这题好多人都用 vector 来做,我这里就用队列来做吧。

首先先讲点队列的知识。B3616 【模板】队列 这题是个不错的队列模板题。

  • <queue> 这是头文件。

  • queue <int> q 定义一个 int 类型的队列。

  • push(x) 向队列中加入一个数 x x x

  • pop() 将队首弹出。

  • front() 输出队首元素。

  • size() 输出此时队列内元素个数。

思路

这题有点像 P1996 约瑟夫问题,我们可以先进行取模,这样可以避免循环过多,然后一直循环,标出要删除的孩子的位置。删除我们可以运用队列中的 pop 进行删除操作。

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <climits>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <ctime>
#include <string>
#include <cstring>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
	inline int read() {
		register int x = 0, f = 1;
		register char c = getchar();
		while (c < '0' || c > '9') {
			if(c == '-') f = -1;
			c = getchar();
		}
		while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
		return x * f;
	}
	inline void write(int x) {
		if(x < 0) putchar('-'), x = -x;
		if(x > 9) write(x / 10);
		putchar(x % 10 + '0');
		return;
	}
}
using namespace fastIO;
int n, k, child[105];
queue <int> children;
int main() {
	cin >> n >> k; 
	for (int i = 1; i <= k; i ++) {
		cin >> child[i];
	}
	for (int i = 1; i <= n; i ++) {
		children.push(i); //进队 
	}
	for(int i = 1;i <= k;i++) {
		child[i] %= children.size();  //防止循环次数过多,而TLE 
		for (int j = 1; j <= child[i]; j ++) {
			children.push (children.front());
			children.pop();
		}
		cout << children.front() << " ";
		children.pop(); //出队 
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值