问题描述
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 11 to 𝑛n . In the beginning, the first child is considered the leader. The game is played in 𝑘k steps. In the 𝑖i -th step the leader counts out 𝑎𝑖ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.
For example, if there are children with numbers [8,10,13,14,16][8,10,13,14,16] currently in the circle, the leader is child 1313 and 𝑎𝑖=12ai=12 , then counting-out rhyme ends on child 1616 , who is eliminated. Child 88 becomes the leader.
You have to write a program which prints the number of the child to be eliminated on every step.
输入格式
The first line contains two integer numbers 𝑛n and 𝑘k ( 2<=𝑛<=1002<=n<=100 , 1<=𝑘<=𝑛−11<=k<=n−1 ).
The next line contains 𝑘k integer numbers 𝑎1,𝑎2,...,𝑎𝑘a1,a2,...,ak ( 1<=𝑎𝑖<=1091<=ai<=109 ).
输出格式
Print 𝑘k numbers, the 𝑖i -th one corresponds to the number of child to be eliminated at the 𝑖i -th step.
题意翻译
n 个孩子在玩一个游戏。 孩子们站成一圈,按照顺时针顺序分别被标号为 1 到 n。开始游戏时,第一个孩子成为领导。 游戏进行 k 轮。 在第 i 轮中,领导会从他顺时针方向下一个孩子开始数 ai 个孩子。最后数到的那个孩子出局,再下一个孩子成为新的领导。
举个例子, 现在圈内还剩 [8, 10, 13, 14, 16]5个孩子,领导编号为 13 , ai = 12。那么出局的孩子为 16 。第 8 个孩子成为下一个领导。
你需要写一个代码模拟这个过程,求出每轮比赛出局的孩子。
第一行包含两个整数 n 和 k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1).
第二行包含 k 个整数 a1, a2, ..., ak (1 ≤ ai ≤ 109).
输出 k 个整数,第 i 个整数表示第 i轮出局的孩子。
输入输出样例
输入 #1
7 5 10 4 11 4 1
输出 #1
4 2 5 6 1
输入 #2
3 2 2 5
输出 #2
3 2
解题思路
- 创建vector用于存放孩子对应的序号
- 用temp来指代每轮的出局孩子对应的序号
- 使用p.at(temp)来访问对应的数据,再将该位置的数据删除
- 使用取模运算防止数据溢出,p.size()为当前vector的长度
一开始先想到了用链表或者数组来存n个孩子所对应的序号,再用数组存每轮要数的数字,使用变量temp存要淘汰的孩子对应的序号,然后把这个序号删除,接着再开始数。
在实现的过程中,发现链表实现起来比较困难,于是使用vector。在求出淘汰孩子对应的序号时,应该先进行取模运算,防止溢出。
话不多说,上代码
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int num[100] = { 0 };
vector<int>p;
int n, k, temp = 0;
int i, j;
cin >> n >> k;
for (i = n; i >= 1; i--) {
p.insert(p.begin()+0,i);
}
for (j = 1; j <= k; j++) {
cin >> num[j];
}
for (j = 1; j <= k; j++) {
temp = (temp + num[j]) % (p.size());//防止溢出
cout << p.at(temp) << ' ';
p.erase(p.begin() + temp);
}
return 0;
}
希望大家都能顺利AC!!!