公式

A - 重複除去ログ / Deduplicated Log 解説 by admin

gpt-5.3-codex

Overview

This is a simulation problem where you look at the given sequence from the beginning, discard an element if it’s the same as the last recorded value, and record it otherwise. In other words, you need to construct a sequence with only consecutive duplicates removed.

Analysis

The key observation is that only the last element of the recorded list is needed for the decision. Whether to add a new event code \(x\) is determined by:

  • The recorded list is empty
  • Or the last element of the recorded list \(\neq x\)

In either case, we add it. Otherwise (same as the last element), we do not add it.

For example, when \(A = [5,5,2,2,2,7,5,5]\):

  • Add 5 → [5]
  • Next 5 is the same as the last element, so skip → [5]
  • Add 2 → [5,2]
  • Next 2,2 are skipped → [5,2]
  • Add 7 → [5,2,7]
  • Add 5 (different from last element 7) → [5,2,7,5]
  • Next 5 is skipped → [5,2,7,5]

The final result is [5,2,7,5].

A naive implementation that “compares with all previous elements each time” would be \(O(N^2)\) in the worst case, which is too slow for \(N \le 5\times10^5\). Since this problem only requires comparison with the last element, each decision can be made in \(O(1)\), and the entire process runs in \(O(N)\).

Algorithm

  1. Prepare an empty array res (the recorded list).
  2. Iterate through the input sequence from the beginning, processing each element as x.
  3. If res is empty or res[-1] != x, append x to res.
  4. Otherwise, do nothing (skip).
  5. Finally, output res separated by spaces.

The provided code implements this procedure directly.

Complexity

  • Time complexity: \(O(N)\) Each element is examined once, with only a comparison to the last element and a possible append.
  • Space complexity: \(O(N)\) The output array res can contain up to \(N\) elements.

Implementation Notes

  • In Python, writing if not res or res[-1] != x: safely combines the empty array check and the last element comparison (when the array is empty, res[-1] is never accessed due to short-circuit evaluation).

  • Since the input size can be large, it’s safer to use sys.stdin.readline.

  • The output can be printed space-separated with print(*res).

    Source Code

import sys

def main():
    input = sys.stdin.readline
    n = int(input().strip())
    a = list(map(int, input().split()))

    res = []
    for x in a:
        if not res or res[-1] != x:
            res.append(x)

    print(*res)

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.3-codex.

投稿日時:
最終更新: