问题 A: DS循环链表—约瑟夫环(Ver. I - A)
时间限制: 1 Sec 内存限制: 128 MB
题目描述
N个人坐成一个圆环(编号为1 - N),从第S个人开始报数,数到K的人出列,后面的人重新从1开始报数。问最后剩下的人的编号。
例如:N = 3,K = 2,S = 1。2号先出列,然后是1号,最后剩下的是3号。
要求使用循环链表实现。
输入
第一行输入t,表示有t个测试用例;
第二行起,每行输入一组数据,包括3个数N、K、S,表示有N个人,从第S个人开始,数到K出列。(2 <= N <= 10^6,1 <= K <= 10, 1 <= S <= N)
输出
出列的人的编号
样例输入
2
13 3 1
3 2 1
样例输出
3 6 9 12 2 7 11 4 10 5 1 8 13
2 1 3
#include<iostream> //第一题非循环链表
#include<algorithm>
#include<cmath>
#include<string>
using namespace std;
#include<queue>
int main()
{
int t;
cin >> t;
while (t--)
{
queue<int> a;
while (!a.empty())
{
a.pop();
}
int n, k, s, temp;
cin >> n >> k >> s;
for (int i = 1; i <= n; ++i)
{
a.push(i);
}
for (int i = 1; i < s; ++i)
{
temp = a.front();
a.pop();
a.push(temp);
}
int count = 0;
//while (!a.empty())
//{
// cout << a.front() << " "; // Output the 1st element
// a.pop(); // Delete the 1st element
//}
while (a.size())
{
count++;
temp = a.front();
a.pop();
if (count % k == 0)
{
cout << temp << " ";
}
else
{
a.push(temp);
}
}
cout << endl;
while (!a.empty())
{
a.pop();
}
}
return 0;
}