【算法百题之三】经典约瑟夫环问题
大家好,我是Lampard~~
很高兴又能和大家见面了,接下来准备系列更新的是算法题,一日一练,早日升仙!
今天的问题是:
一堆人围圈圈,按顺序报数,报到3的出列,然后接下来的人继续从1报起,直至所有人都出列为止。
(默认初始的人按顺序存放在一维数组中)
下面是我解题的思路:
(请把所有的栈字改成队列.....脑子一抽写错了)
新建两个队列AB
第一步把数组中出列的数据输出,非出列的数据转到队列A中
第二步把队列A中出列的元素输出,非出列的数据转到队列B中
第三步把队列B中出列的元素输出,非出列的数据转到队列A中
...
直至所有的数据都输出,两个队列都为空为止
#include "pch.h"
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main()
{
string name[] = {"小一","小二","小三","小四","小五","小六","小七","小八"};
// 开始的名字按顺序存放在一维数组里面
int num = 1;
// num是报数的数字,当num==3时出列
queue <string> A;
queue <string> B;
// 第一步把一维数组里面的名字转进去队列A处
for (int i = 0; i < (sizeof(name)/sizeof(name[0])); i++)
{
if (num == 3)
{
cout << name[i] << "出列" <<endl;
num = 1;
}
else
{
num++;
A.push(name[i]);
}
}
int flag = 1;
// flag是判断队列AB是否都为空,flag==1时,A非空,flag == 2时,B非空,flag == 0时,AB都为空
while (flag != 0)
{
if (flag == 1)
{
// c从队列A转队列B
while (A.size() != 0)
{
if (num == 3)
{
cout << A.front() << "出列" << endl;
num = 1;
A.pop();
}
else
{
num++;
B.push(A.front());
A.pop();
}
}
// 判断B是否为空
if (B.size() != 0)
flag = 2;
else
flag = 0;
}
else if (flag == 2)
{
while (B.size() != 0)
{
if (num == 3)
{
cout << B.front() << "出列" << endl;
num = 1;
B.pop();
}
else
{
num++;
A.push(B.front());
B.pop();
}
}
// 判断A是否为空
if (A.size() != 0)
flag = 1;
else
flag = 0;
}
}
}
测试结果: