- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 50 lines of C++ from the credited upstream file 1116.cpp.
- The implementation keeps its working state in language-native values and containers.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123#include <semaphore.h>4 5class ZeroEvenOdd {6 public:7 ZeroEvenOdd(int n) : n(n) {8 sem_init(&zeroSemaphore, 0, 1);9 sem_init(&evenSemaphore, 0, 0);10 sem_init(&oddSemaphore, 0, 0);11 }12 13 ~ZeroEvenOdd() {14 sem_destroy(&zeroSemaphore);15 sem_destroy(&evenSemaphore);16 sem_destroy(&oddSemaphore);17 }18 19 20 void zero(function<void(int)> printNumber) {21 for (int i = 0; i < n; ++i) {22 sem_wait(&zeroSemaphore);23 printNumber(0);24 sem_post(&(i % 2 == 0 ? oddSemaphore : evenSemaphore));25 }26 }27 28 void even(function<void(int)> printNumber) {29 for (int i = 2; i <= n; i += 2) {30 sem_wait(&evenSemaphore);31 printNumber(i);32 sem_post(&zeroSemaphore);33 }34 }35 36 void odd(function<void(int)> printNumber) {37 for (int i = 1; i <= n; i += 2) {38 sem_wait(&oddSemaphore);39 printNumber(i);40 sem_post(&zeroSemaphore);41 }42 }43 44 private:45 const int n;46 sem_t zeroSemaphore;47 sem_t evenSemaphore;48 sem_t oddSemaphore;49};50