返回学习页
知识点指南

Simulation

Simulation means modelling a process exactly as it happens. You keep the current state, apply each event in order, and make sure every update matches the operation rules in the story.

什么时候使用

读题时可以留意这些信号。

  • The statement describes actions happening step by step.
  • The answer depends on the final state after a sequence of events.
  • The process has rules such as move, recharge, toggle, transfer, or transform.

常见错误

提交前可以检查这些小陷阱。

  • Updating state before checking the condition that uses the old state.
  • Processing events out of order.
  • Forgetting boundary or impossible-state rules.

怎么写成代码

把知识点翻译成变量、循环、判断和更新。

  • Define state variables that describe the current situation.
  • Loop through events or commands in the order they happen.
  • For each event, update state in the exact order described by the story.
  • After all events, output the requested part of the final state.

在 Block 题里长什么样

答题时通常会看到这些步骤被拆成代码块。

  1. 1Read the number of events.
  2. 2Initialise the starting state.
  3. 3Loop over events.
  4. 4Decode the current event.
  5. 5Apply the event rule.
  6. 6Output final state or decision.

题目里怎么出现

读题时先找这些信号,再决定答案区应该选哪些 blocks。

  • The story uses words like after, next, current, before, command, or process.
  • Changing update order would change the answer.
  • A brute-force step-by-step version is acceptable for the constraints, or a repeated cycle must be recognised.

Apply ordered events

一个小型模板,展示代码和 blocks 的对应关系。

C++

int position = 0;
for (char command : commands) {
    if (command == 'R') position++;
    if (command == 'L') position--;
}
cout << position << '\n';

Python

position = 0
for command in commands:
    if command == 'R':
        position += 1
    if command == 'L':
        position -= 1
print(position)

对应 block 顺序

  1. 1Read the commands.
  2. 2Initialise the starting state.
  3. 3Loop through commands in order.
  4. 4Check which command occurred.
  5. 5Update the state.
  6. 6Print the final state.

建议先练这道题

可以先从 Soccer Match 开始,再回到这里复盘知识点信号。

打开题目