Rock is playing Snakes and Ladders on a board with $N$ cells, numbered from $1$ to $N$.
He starts at cell $1$. On each turn, he rolls a die and moves forward by $1$ to $6$ cells. If he lands on the bottom of a ladder, he immediately climbs to its top. If that cell is also the bottom of another ladder, he continues climbing.
There are $K$ ladders. Ladder $i$ goes from $A_i$ to $B_i$ and all ladders satisfy: $$ 1<A_1<B_1\le A_2<B_2\le\cdots\le A_K<B_K<N $$
Rock wins if he reaches cell $N$.
Before the game starts, you may place at most $6$ snakes. A snake from $X$ to $Y$ must satisfy $1\le Y<X<N$. If Rock lands on $X$, he immediately moves to $Y$.
After Rock moves according to his dice roll:
- If he lands on the bottom of a ladder, he immediately moves to the top of that ladder.
- If he lands on the head of a snake, he immediately moves to the tail of that snake.
- If the new cell is again the bottom of a ladder or the head of a snake, the corresponding move is applied again.
A snake head cannot be placed at the bottom of a ladder, i.e. $X\neq A_i$ for all $1\le i\le K$.
Construct at most $6$ snakes such that Rock can never reach cell $N$, no matter what he rolls.
Input
The first line contains two integers $N$ and $K$.
The next $K$ lines each contain two integers $A_i$ and $B_i$.
Output
Output an integer $S$ $(0\le S\le6)$, the number of snakes.
Then output $S$ lines. Each line contains two integers $X$ and $Y$, describing a snake from $X$ to $Y$.
No two snakes may have the same head.
Constraints
For all cases: $8\le N\le2\times10^5,\ 0\le K\le2\times10^5$
Subtask 1 (15%): $K=0$
Subtask 2 (20%): $A_i>7$ for all $1\le i\le K$
Subtask 3 (30%): $B_i<A_{i+1}$ for all $1\le i<K$
Subtask 4 (35%): No additional constraints
Notes
It is guaranteed that a valid solution using at most $6$ snakes always exists.
Sample Test Cases
| Input | Output | |
|---|---|---|
| 16 2 2 5 8 13 |
5 3 1 4 2 5 1 6 3 7 4 |
|
One possible answer uses five snakes. For example, landing on cell $7$ triggers the snake to $4$, then another snake to $2$, the ladder to $5$, and finally the snake to $1$. |
||
| 50 10 2 3 3 4 4 5 5 6 8 12 12 15 15 20 21 28 28 35 35 49 |
2 6 1 7 5 |
|
One possible answer uses two snakes. If Rock lands on cell $7$, the snake takes him to $5$, then the ladder and the other snake take him back to cell $1$. |
||
Scoring: Per Subtask
Authored by s19x17
Appeared in 2026 Wah Yan Interschool Olympiad in Informatics 🤯🥷⚡🧠🏆