数据结构 击鼓传花 (STL+模拟)

Description

设有N个人围成一个圈,每人手里都握着一个令牌写明一个 数字(随机生成的)。从第一个人开始玩“击鼓传花”游戏,第一个击的次数为其令牌上写明的数字数(假设为m1)。第m1个人出列。下次再从第m1+1个人 开始新的“击鼓传花”击的次数也为其令牌上写明的次数,等于该次数的人出列。重复以上过程直到所有人都出列为止。

Input

输入第一行为测试数据组数。每组测试数据2行,第1行一个整数n(1<=n<=10000),代表人数,第2行有n个空格隔开的整数代表mi(1<=mi<=5000)。

Output

对每组测试数据输出2行,第1行为数据组数,第2行为所有人顺序出队的序列,格式见样例。

Sample Input

1
5
1 2 3 4 5

Sample Output

Case #1:
2 1 3 4

HINT

考察知识点:循环链表,时间复杂度O(sum{m}),空间复杂度O(n)


从1开始,传1次:1->2。2出列。

从3开始,传3次:3->4->5->1。1出列。

从3开始,传3次:3->4->5->3。3出列。

从4开始,传4次:4->5->4->5->4。4出列。


Append Code

析:这个题用dqueue模拟就好,这个STL遍历快,用 list 可能要超时。就是每次都计算好下一次要到的位置,然后直接去访问,而不是遍历。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <list>
#include <deque>
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
#define frer freopen("in.txt", "r", stdin)
#define frew freopen("out.txt", "w", stdout)
using namespace std;
 
typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e4 + 5;
const int mod = 1e9 + 7;
const char *mark = "+-*";
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline int Min(int a, int b){ return a < b ? a : b; }
inline int Max(int a, int b){ return a > b ? a : b; }
inline LL Min(LL a, LL b){ return a < b ? a : b; }
inline LL Max(LL a, LL b){ return a > b ? a : b; }
inline bool is_in(int r, int c){
    return r >= 0 && r < n && c >= 0 && c < m;
}
 
deque<int> dq;
int a[maxn];
deque<int> :: iterator it;
 
int main(){
    int T;  cin >> T;
    for(int kase = 1; kase <= T; ++kase){
        printf("Case #%d:
", kase);
        scanf("%d", &n);
        dq.clear();
        for(int i = 0; i < n; ++i){
            scanf("%d", &a[i]);
            dq.push_back(i+1);
        }
 
        m = 0;
        m = (m + a[m]) % dq.size();
        printf("%d", dq[m]);
 
        dq.erase(dq.begin()+m);
        m %= dq.size();
        int x = dq[m];
        for(int i = 1; i < n-1; ++i){
            m = (m + a[x-1]) % (int)dq.size();
            if(i == 1)  printf(" %d", dq[m]);
            else printf(" %d", dq[m]);
 
            dq.erase(dq.begin()+m);
            m %= dq.size();
            x = dq[m];
        }
        printf("
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/dwtfukgv/p/5875511.html