Follow the MESI states

The MESI protocol gives every cached copy of a block one of four states: Modified, Exclusive, Shared or Invalid. Follow the states of one block in every core as the cores read and write it.

What to build

A program that prints the state of the block in each core after every operation, and the number of writebacks.

Requirements

  • All cores start Invalid. A read by a core that is already M, E or S changes nothing.
  • A read by an Invalid core: every other core that holds the block becomes Shared (a Modified one first writes the block back to memory, counting one writeback), and the reader becomes Shared if another core held the block, otherwise Exclusive.
  • A write by any core: a Modified copy in another core is first written back (one writeback), then all other cores become Invalid and the writer becomes Modified. A write by a core that is already Modified changes nothing.
  • After every operation print the states of cores 0 to c − 1 as letters separated by spaces. At the end print writebacks W.

Input

A line with c, a line with n, then n lines R core or W core.

Output

n + 1 lines.

Constraints

1 ≤ c ≤ 6; 1 ≤ n ≤ 50.

Example

Input:

3
5
R 0
R 1
W 1
R 0
W 2

Output:

E I I
S S I
I M I
S S I
I I M
writebacks 1

Why it works

MESI makes sure there is never a stale copy: a writer must be the only holder, so it invalidates the others, and a reader of a Modified block must get the fresh data, so the owner writes back and drops to Shared.

Examples

Example 1 · Input
3
5
R 0
R 1
W 1
R 0
W 2
Expected output
E I I
S S I
I M I
S S I
I I M
writebacks 1
Example 2 · Input
2
3
W 0
W 1
R 0
Expected output
M I
I M
S S
writebacks 2

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Keep a list of states, one per core, all starting at I.

Hint 2

Read by c when its state is I: look at the other cores that are not I. If one is M, count a writeback. All those cores become S. Core c becomes S if there were any, otherwise E. A read in M, E or S changes nothing.

Hint 3

Write by c: if another core is M, count a writeback. All other cores become I and core c becomes M.

Solution

Show one correct solution (try it yourself first)
c = int(input())
n = int(input())
st = ["I"] * c
wb = 0
for _ in range(n):
    op, core = input().split()
    core = int(core)
    if op == "R":
        if st[core] == "I":
            others = [i for i in range(c) if i != core and st[i] != "I"]
            for i in others:
                if st[i] == "M":
                    wb += 1
                st[i] = "S"
            st[core] = "S" if others else "E"
    else:
        for i in range(c):
            if i != core and st[i] == "M":
                wb += 1
            if i != core:
                st[i] = "I"
        st[core] = "M"
    print(" ".join(st))
print("writebacks", wb)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Cache coherence and the MESI protocol →