Under construction

Still being built. Things may change

Count the Operations

Time limit2sMemory limit2048 MB

Summary
Given a loop over 0 to n-1 with conditional jumps i = y when i == x, count the operations performed or report -1 if the loop never ends.
Level

Medium6 of 10

Topics
Simulation, Graph, Implementation
Solved
No attempts yet

Statement

In a class, Ania wrote a program that does some work for all integers from 0 to n−1n - 1:

for (int i = 0; i < n; i++) {
    work (i);
}

The teacher Petia looked at the program and said it would take too long, since the maximum value of nn is 10910^{9}.

So Ania decided to do the work for only some of the numbers. Her new program is:

for (int i = 0; i < n; i++) {
    if (i == x_1) i = y_1;
    if (i == x_2) i = y_2;
    ...
    if (i == x_k) i = y_k;
    work (i);
}

Count how many operations this program performs for a given nn, and determine whether it terminates. The counted operations are assignments (i = 0, i++, i = y\_1, ...), comparisons (i < n, i == x\_1, ...), and the work itself (work (i)).

Input

The input contains Ania's program, formatted exactly as in the examples. The opening curly bracket is on the line with for, there is a space before every opening round bracket, and the indentation is four spaces. No line ends with a space.

The number of lines with conditionals is kk, where 0≤k≤1050 \le k \le 10^{5}. The constraints on the values are 0≤xi,yi<n≤1090 \le x_i, y_i < n \le 10^{9}. Other values have no constraints. The line with work appears once, after all the if lines.

Output

Print the number of operations the program performs. If the program never terminates, print -1.

Examples2

  1. Example 1

    Input
    for (int i = 0; i < 3; i++) {
        work (i);
    }
    
    Expected output
    11
    
  2. Example 2

    Input
    for (int i = 0; i < 5; i++) {
        if (i == 3) i = 1;
        if (i == 1) i = 3;
        if (i == 3) i = 4;
        work (i);
    }
    
    Expected output
    16