【HDU 1276】士兵队列训练问题(两个队列模拟)

题目链接

题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1276

解题思路

两个队列模拟即可,注意:

  1. 必须每一轮都点完,而不是数到只剩三人了就停止。
  2. 如果本来就不大于三个人,直接输出。

代码如下(G++)

#include <bits\stdc++.h>

using namespace std;
typedef long long ll;
double eps = 1e-7;

//ofstream out("out1.txt");

int main() {
    int t;
    cin >> t;
    int n;
    while (t--) {
        cin >> n;
        queue<int> a, b;
        for (int i = 1; i <= n; ++i) {
            a.push(i);
        }

        //模拟操作,先2后3
        while (a.size() > 3 or b.size() > 3) {
            int cnt = 0;
            while (a.size()) {
                int x = a.front();
                a.pop();
                if (++cnt % 2 != 0) {
                    b.push(x);
                }
            }
            if(b.size() <= 3) break;

            cnt = 0;
            while (b.size()) {
                int x = b.front();
                b.pop();
                if (++cnt % 3 != 0) {
                    a.push(x);
                }
            }
        }

        //将余下的数字加入数组并排序输出
        //a和b只可能有一个不为空
        int p[3];
        int cnt = 0;
        while (a.size()) {
            p[cnt++] = a.front();
            a.pop();
        }
        while (b.size()) {
            p[cnt++] = b.front();
            b.pop();
        }

        sort(p, p + cnt);
        for (int i = 0; i < cnt; ++i) {
            if (i != 0) cout << " ";
            cout << p[i];
        }
        cout << endl;
    }
    return 0;
}

posted @ 2019-09-06 01:10  ninding  阅读(287)  评论(0编辑  收藏  举报