类约瑟夫游戏,好像是可以用数学的方式计算出来….但是….
那么模拟一下这个游戏,士兵们编好号放入链表中,然后不断出列,直到剩下3个人。
注意it = ls.erase(it);
//HDU1276
#include <cstdio>
#include <list>
using namespace std;
list<int> ls;
int main(int argc, char const *argv[]) {
int t;
scanf("%d", &t);
while (t--) {
ls.clear();
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
ls.push_back(i);
}
list<int> :: iterator it;
bool flag2 = true;
while (ls.size() > 3) {
if (flag2) {
int cnt = 1;
for (it = ls.begin(); it != ls.end(); ) {
if (cnt == 2) {
it = ls.erase(it);
cnt = 1;
} else {
cnt++;
it++;
}
}
flag2 = false;
} else {
int cnt = 1;
for (it = ls.begin(); it != ls.end(); ) {
if (cnt == 3) {
it = ls.erase(it);
cnt = 1;
} else {
cnt++;
it++;
}
}
flag2 = true;
}
}
for (it = ls.begin(); it != ls.end(); it++) {
if (it != ls.begin()) {
putchar(' ');
}
printf("%d", *it);
}
putchar('\n');
}
return 0;
}