Official

E - Permute K times 2 Editorial by MMNMM


頂点 1,1, 頂点 2,,2,\ldots, 頂点 NN からなり、iPi (1iN)i\to P _ i\ (1\leq i\leq N)NN 辺がある有向グラフを考えます。
このグラフにおいて、ii から kk 回進んだ頂点を PikP ^ k _ i と呼ぶことにします(どの頂点についてもその頂点から出る辺は 11 本のみであるため、これは一意に定まります)。

求める答えは (Pi2K)i(P ^ {2 ^ K} _ i) _ i です(証明は省略しますが、KK についての帰納法で示すのが平易だと思います)。

有向グラフはいくつかのサイクルに分けることができます。 それぞれのサイクルについて、2K2 ^ K をそのサイクルの長さで割った余りを考えれば最終的な値を求めることができます。

サイクルの個数を MM として時間計算量は O(N+MlogK)O(N+M\log K) となります。

実装例は以下のようになります。

Copy
  1. #include <atcoder/math>
  2. #include <iostream>
  3. #include <vector>
  4. int main() {
  5. using namespace std;
  6. unsigned N;
  7. unsigned long K;
  8. cin >> N >> K;
  9. vector<unsigned> P(N);
  10. for (auto &p : P) {
  11. cin >> p;
  12. --p;
  13. }
  14. // 求める順列
  15. vector<unsigned> ans(N);
  16. // used[i] := i に対する答えをすでに求めていれば true
  17. basic_string used(N, false);
  18. for (unsigned i{}; i < N; ++i) if (!used[i]) {
  19. // i を含むサイクルを求める
  20. vector<unsigned> cycle;
  21. {
  22. unsigned j{i};
  23. while (!used[j]) {
  24. used[j] = true;
  25. cycle.push_back(j);
  26. j = P[j];
  27. }
  28. }
  29. // サイクルに対して答えを求める
  30. const auto cycle_length{size(cycle)};
  31. const auto shift{atcoder::pow_mod(2, K, cycle_length)};
  32. for (unsigned j{}; j < cycle_length; ++j)
  33. ans[cycle[j]] = cycle[(j + shift) % cycle_length];
  34. }
  35. for (const auto p : ans)
  36. cout << p + 1 << " ";
  37. cout << endl;
  38. return 0;
  39. }
#include <atcoder/math>
#include <iostream>
#include <vector>

int main() {
    using namespace std;
    unsigned N;
    unsigned long K;
    cin >> N >> K;
    vector<unsigned> P(N);
    for (auto &p : P) {
        cin >> p;
        --p;
    }

    // 求める順列
    vector<unsigned> ans(N);
    // used[i] := i に対する答えをすでに求めていれば true
    basic_string used(N, false);
    for (unsigned i{}; i < N; ++i) if (!used[i]) {
        // i を含むサイクルを求める
        vector<unsigned> cycle;
        {
            unsigned j{i};
            while (!used[j]) {
                used[j] = true;
                cycle.push_back(j);
                j = P[j];
            }
        }
        // サイクルに対して答えを求める
        const auto cycle_length{size(cycle)};
        const auto shift{atcoder::pow_mod(2, K, cycle_length)};
        for (unsigned j{}; j < cycle_length; ++j)
            ans[cycle[j]] = cycle[(j + shift) % cycle_length];
    }
    
    for (const auto p : ans)
        cout << p + 1 << " ";
    cout << endl;
    return 0;
}

posted:
last update:



2025-04-09 (Wed)
02:39:23 +00:00