公式

B - 伯爵の金庫 / The Count's Vault 解説 by admin 印刷ページ

swe-2-high

Solution

This problem only requires simulating the \(N\) transactions in order, maintaining a single variable for the number of gold coins in the vault.

Initialize a variable \(\mathrm{cur}\) to \(X\), the initial number of coins. For each transaction \(i\):

  • If \(T_i = \) D, add \(A_i\) to \(\mathrm{cur}\).
  • If \(T_i = \) W, subtract \(A_i\) from \(\mathrm{cur}\) only when \(\mathrm{cur} \geq A_i\). If \(\mathrm{cur} < A_i\), the transaction is declined, so do nothing.

Print \(\mathrm{cur}\) after each transaction is processed. There is no need to store the input in an array — each transaction can be processed as it is read — so input-related memory is also constant.

Proof of Correctness

Claim: Immediately after processing transaction \(i\), \(\mathrm{cur}\) equals the number of coins in the vault.

Proof (by induction on \(i\)):

  • Base case: Before any transaction, \(\mathrm{cur} = X\), matching the initial state in the statement.
  • Inductive step: Assume \(\mathrm{cur}\) equals the vault’s contents right after transaction \(i-1\).
    • If \(T_i = \) D, the vault should gain \(A_i\) coins, and we indeed set \(\mathrm{cur} \leftarrow \mathrm{cur} + A_i\).
    • If \(T_i = \) W and \(\mathrm{cur} \geq A_i\), the vault holds at least \(A_i\) coins so the withdrawal is accepted, and \(\mathrm{cur} \leftarrow \mathrm{cur} - A_i\) is the correct new balance.
    • If \(T_i = \) W and \(\mathrm{cur} < A_i\), the transaction is declined and the contents do not change; we leave \(\mathrm{cur}\) unchanged, which is correct.

Hence every printed value is correct. ∎

Complexity

  • Time: \(O(N)\) — each transaction is handled in constant time.
  • Space: \(O(1)\) auxiliary — only the balance and loop variables are kept; the input is not stored in an array.

Implementation Notes

The maximum balance is at most about \(X + \sum A_i \leq 1000 + 100 \times 1000 = 101000\), which fits in a 32-bit integer, but using a 64-bit integer (long long in C++) is a safe habit. The Python solution also processes each line as it is read; only the output strings are accumulated (writing output line by line would make the auxiliary space strictly \(O(1)\)).

投稿日時:
最終更新: