top of page

Straightforwardly and naively simulating the process

Introduction

Simulation is a common technique for beginner problems involving simply simulating the process. Nevertheless, you need to simulate in a way efficient enough for the bounds and that works. This is often used when we need to find the end result of some process or find when something occurs. These problems usually use knowledge of built-in data structures and keeping track of things using variables.

Example - Cirno and Operations

Consider the following Codeforces problem: Cirno and Operations

Notice that N is very small. This means that we can directly simulate the two array operations, however, we must do it greedily. Since transforming it into the difference array reduces the length by 1, we can consider N - 1 difference array operations. To start, set the answer to the sum of the array as a candidate for the maximum sum. Then, for each iteration, we consider the difference array and the difference array of the reverse array. We change the array to whichever has the greater sum, and continue to the next iteration.

image.png

Example - Mixing Milk

The next USACO problem: Mixing Milk

See if you can solve this before reading the solution!

Solution: To solve this, we simply simulate the 100 pours, keeping track of the amount of milk in each bucket. Moreover, if we pour pail a with an amount of milk x to pail b with an amount of milk y and capacity c, the amount of milk we pour (until pail a becomes empty or pail b becomes full) is ​min(x, c - y). We then subtract this amount from x and add this amount to y:

This is sufficient for full credit. Thinking beyond the problem, if the number of pours were as large as 10⁹, simply simulating all the operations would exceed the time limit. Instead, we recognize that the 3rd, 4th, and 5th pours repeat in a cycle for each 3 pours (as said in the sample):

3rd pour: 10 0 2

4th pour: 0 10 2 

5th pour: 0 0 12

6th pour: 10 0 2

7th pour: 0 10 2

8th pour: 0 0 12

...

Since 100 mod 3 = 1 and 10⁹ mod 3 = 1, we can simulate up to the 4th operation for both cases:

image.png
image.png

Conclusion

Simulating the process is a good way to solve problems directly, but always consider whether this works within the problem constraints!

🧩 Mini-Challenge 🧩

[Work in progress]

💡 Mini-Challenge Solution 💡

[Work in progress]

⚔️ Problems ⚔️

📊 Poll 📊

Vote on this interactive poll to share your opinion on different aspects of competitive programming such as favorite algorithm, data structure, or most challenging problem with real-time results!

bottom of page