公式

B - 円形カード回し / Circular Card Rotation 解説 by admin 印刷ページ

gpt-5.3-codex

Overview

Since the cards simply “rotate one position clockwise as a whole” each time, the state after \(K\) operations can be determined in one shot as the result of shifting by \(K \bmod N\).

Analysis

The essence of this operation is that each card advances one person clockwise per operation.
That is, card number \(x\) is initially held by child \(x\), after 1 operation it is held by child \(x+1\), after 2 operations by child \(x+2\), and so on (all cyclic modulo \(N\)).

Conversely, “the card held by child \(i\) after \(K\) operations” is: - the card that originally belonged to the child \(K\) positions counterclockwise.

Expressing this as a formula, with \(s = K \bmod N\):

[ \text{ans}[i] = ((i - s - 1) \bmod N) + 1 ]

(where \(i\) is 1-indexed).


Why the naive solution doesn’t work

If you naively “simulate one operation at a time,” each operation takes \(O(N)\), for a total of \(O(NK)\).
However, since \(K \le 10^{18}\), this is far too slow.


How to solve it

Movement on a circular arrangement has period \(N\), so after \(N\) moves everything returns to its original state.
Therefore, what matters is not \(K\) itself but only \(K \bmod N\).
Then, for each child, we can directly compute the card number using the formula above, yielding the answer in a single pass.

Algorithm

  1. Read \(N, K\).
  2. Compute \(s = K \bmod N\).
  3. For each \(i=1..N\), compute
    [ card = ((i - s - 1) \bmod N) + 1 ] and append it to the output array.
  4. Output separated by newlines.

Complexity

  • Time complexity: \(O(N)\)
  • Space complexity: \(O(N)\) (for storing the output in an array; this can be reduced to \(O(1)\) with sequential output)

Implementation Notes

  • Python’s % operator normalizes negative numbers to non-negative values, so (i - s - 1) % N safely handles cyclic indexing.

  • Since the problem uses 1-indexed numbering, the -1 and +1 in the formula adjust for the offset.

  • Because \(K\) can be extremely large, it is crucial to compute K % N first.

    Source Code

import sys

def main():
    N, K = map(int, sys.stdin.readline().split())
    s = K % N
    out = []
    for i in range(1, N + 1):
        card = ((i - s - 1) % N) + 1
        out.append(str(card))
    sys.stdout.write("\n".join(out))

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.3-codex.

投稿日時:
最終更新: