队列之士兵报数

队列基础数据结构的小练习~

现在输入一个正整数n,代表n名士兵编号1-n,开始报数,先1212报数报到2者出列;然后123123报数报到3者出列;然后又1212报数···直到只剩下小于等于3个人,输出这三个人的编号。

例:

输入:20

输出:1 7 19

代码:

 1 #include 
 2 using namespace std;
 3 int que[10001] = { 0 };
 4 int main()
 5 {
 6     int n;
 7     cin >> n;
 8     int head = 1, tail = 1;
 9     for (int i = 1; i <= n; i++) que[tail++] = i;
10     while (1)
11     {
12         n = tail - head;
13         if (tail - head <= 3)break;
14         for (int i = 1; i <= n; i++)
15         {
16             if (i % 2 == 1)que[tail++] = que[head];
17             head++;
18         }
19         n = tail - head;
20         if (tail - head <= 3)break;
21         for (int i = 1; i <= n; i++)
22         {
23             if (i % 3 != 0)que[tail++] = que[head];
24             head++;
25         }
26     }
27     for (int i = head; i < tail; i++)
28     {
29         cout << que[i] << " ";
30     }
31 }

结果:

 

转载于:https://www.cnblogs.com/ljy1227476113/p/9866101.html

你可能感兴趣的:(队列之士兵报数)