Magic Master(2019年南昌网络赛E题+约瑟夫环)

题目链接

传送门

题意

初始时你有(n)张牌(按顺序摆放),每一次操作你将顶端的牌拿出,然后按顺序将上面的(m)张牌放到底部。

思路

首先我们发下拿走(1)后就变成了总共有(n-1)个人数到(m+1)的人出局,问你每个人是第几个出局的,很明显的约瑟夫环。

比赛的时候我还在推公式,然后发现机房有人用暴力模拟过了,尤其是题解也是暴力,就很无语。

如果这题标程不假并且只给(1s),那么该怎么写呢?

这题由于(n)很大,我们肯定不能将(n)个人出局顺序一一枚举,然后我们发现(q)很小,因此我们就对查询的那个编号进行求解即可。

由于第一个人始终是第一个出局的,那么我们将他特判掉,然后(n=n-1),又由于是数到(m+1)出局,因此令(m=m+1),然后开始解题。

假设当前有(n(ngeq m)人,那么将会出局(m,2m,3m,dots,lfloorfrac{n}{m} floor*m),然后将(lfloorfrac{n}{m} floor*m+1,lfloorfrac{n}{m} floor*m+2,dots,n)和前面没有出局的人拼接起来变成(lfloorfrac{n}{m} floor*m+1,lfloorfrac{n}{m} floor*m+2,dots,n,1,dots),然后更新现在查询的人的编号是多少即可。

注意当(n<m)时,再用上式就会发现没有人出局,因此需要转变思路,每次出局编号为((m-1)\% n+1)(m-1)后再取模加一是处理掉模(n)等于(0)的情况,之后就和上面一样拼接即可,这部分只需要循环(m)次,也就是说最多循环(10)次。

用这种方法只需要跑(2ms),因此这次网络赛给的时限使得这题成为了一道假题。

代码

#include <set>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <bitset>
#include <cstdio>
#include <string>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

typedef long long LL;
typedef pair<LL, LL> pLL;
typedef pair<LL, int> pLi;
typedef pair<int, LL> pil;;
typedef pair<int, int> pii;
typedef unsigned long long uLL;

#define lson (rt<<1)
#define rson (rt<<1|1)
#define lowbit(x) x&(-x)
#define name2str(name) (#name)
#define bug printf("*********
")
#define debug(x) cout<<#x"=["<<x<<"]" <<endl
#define FIN freopen("/home/dillonh/CLionProjects/Dillonh/in.txt","r",stdin)
#define IO ios::sync_with_stdio(false),cin.tie(0)

const double eps = 1e-8;
const int mod = 1000000007;
const int maxn = 200000 + 7;
const double pi = acos(-1);
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3fLL;

int t, n, m, q, x;

int main() {
#ifndef ONLINE_JUDGE
    FIN;
#endif
    scanf("%d", &t);
    while(t--) {
        scanf("%d%d%d", &n, &m, &q);
        ++m;
        while(q--) {
            scanf("%d", &x);
            if(x == 1) {
                printf("1
");
                continue;
            }
            --x;
            int tot = n - 1, ans = 1;
            while(1) {
                if(tot < m) {
                    int nw = (m - 1) % tot + 1;
                    if(nw == x) {
                        printf("%d
", ans + 1);
                        break;
                    }
                    if(nw < x) x = x - nw;
                    else x = tot - nw + x;
                    ++ans, --tot;
                    continue;
                }
                if(x % m == 0) {
                    printf("%d
", ans + (x / m));
                    break;
                }
                ans += tot / m;
                if(x > (tot / m) * m) x = x - (tot / m) * m;
                else x = tot - (tot / m) * m + x - (x / m);
                tot -= tot / m;
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Dillonh/p/11497036.html