Legal state changes

A process is always in one of five states, and only some moves between them make sense: a process cannot go from waiting straight to running.

What to build

Check whether a list of states is a legal life of one process.

Requirements

  • The states are new, ready, running, waiting and terminated. The legal moves are: new to ready; ready to running; running to ready, waiting or terminated; waiting to ready. Nothing may follow terminated.
  • The first state must be new. If it is not, print invalid at step 1.
  • Otherwise print valid if every move is legal, or invalid at step K for the first state (counted from 1) that cannot follow the one before it.

Input

The first line has n (1 ≤ n ≤ 30). The next n words are the states, in order.

Output

One line: valid or invalid at step K.

Constraints

Every word is one of the five state names.

Example

Input:

5
new
ready
running
waiting
ready

Output:

valid

Why it works

The state diagram is a small graph, and a table of allowed moves is the simplest way to hold it. Checking a history means looking at each pair of neighbours once. The kernel does the same check in its own code: waiting can only go to ready, because the process must wait in line for the CPU again.

Examples

Example 1 · Input
5
new
ready
running
waiting
ready
Expected output
valid
Example 2 · Input
3
new
ready
waiting
Expected output
invalid at step 3

Hints

Hint 1

Turn each state name into a number 0 to 4 with strcmp, and write the legal moves as a 5 by 5 table of 0 and 1.

Hint 2

The first state must be new. From then on, check each pair of neighbours with the table.

Hint 3

Nothing may follow terminated, so its row in the table is all zero.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *names[5] = {"new", "ready", "running", "waiting", "terminated"};
    int allowed[5][5] = {
        {0, 1, 0, 0, 0},
        {0, 0, 1, 0, 0},
        {0, 1, 0, 1, 1},
        {0, 1, 0, 0, 0},
        {0, 0, 0, 0, 0},
    };
    int n, state[30];
    char word[16];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%15s", word);
        for (int s = 0; s < 5; s++)
            if (strcmp(word, names[s]) == 0) state[i] = s;
    }
    if (state[0] != 0) {
        printf("invalid at step 1\n");
        return 0;
    }
    for (int i = 1; i < n; i++) {
        if (!allowed[state[i - 1]][state[i]]) {
            printf("invalid at step %d\n", i + 1);
            return 0;
        }
    }
    printf("valid\n");
    return 0;
}

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

Lesson: Processes →