题解:AT_abc013_4 [ABC013D] 阿弥陀

· · 题解

某天闲逛 B 站时看到了疑似用户整活的 AtCoder PV,里面的题我找到了原题。

我觉得这个视频帅爆了,然后就写了宣传片中的题。

思路

我们把 M 根线条称作一个循环节。

首先,用 O(M) 的时间复杂度算出在一个循环节中,从左到右第 i 根线最终到哪里。考虑从下到上加线条,一开始每根线都到它自己,每加一个线条,线条连接的两根竖线就交换它们的答案。我们把每根竖线的答案记作 P。

现在有了一个循环节的 P,我们要求答案 Q,我们让乘法运算 P \times Q 代表对于每一个 i,答案 R_i 为 P_{Q_i}。P^k 代表这种乘法运算下的幂运算。首先,根据其定义,P^{a+b}=P^a \times P^b。然后根据快速幂的原理,我们可以计算 P^1,P^2,P^4\dots P^{2^k} 的排列,然后把 D 二进制拆分的结果,把相应的 P 乘起来,得到答案。时间复杂度为 O(N \log D + M)。

AC CODE:

#include <bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
typedef double lf;
typedef long double ld;
using namespace std;
int n, m, d, a[200100];
vector<int> p, ans; // 该数组记录单个循环节第 i 列的答案
vector<int> mul(vector<int> &a, vector<int> &b) { // 单次乘法
    vector<int> c;
    for (auto i : a) {
        c.push_back(b[i]);
    }
    return c;
}
void fpow(ll x) { // 快速幂
    for (int i = 0; i <= n; i++) ans.push_back(i);
    while (x) {
        if (x & 1) {
            ans = mul(ans, p);
        }
        p = mul(p, p), x >>= 1;
    }
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    cin >> n >> m >> d;
    for (int i = 1; i <= m; i++) {
        cin >> a[i];
    }
    for (int i = 0; i <= n; i++) {
        p.push_back(i);
    }
    for (int i = m; i >= 1; i--) {
        swap(p[a[i]], p[a[i] + 1]);
    }
    fpow(d);
    for (int i = 1; i <= n; i++) {
        cout << ans[i] << '\n';
    }
    return 0;
}