APIO '15 P2 - Jakarta Skyscrapers

View as PDF

Submit solution


Points: 20 (partial)
Time limit: 0.2s
Memory limit: 256M

Problem type

The city of Jakarta has N skyscrapers located on a line, conveniently numbered 0 through N1 from left to right. There are no other skyscrapers in Jakarta.

Jakarta is inhabited by M mystical creatures called "doge"s. The doges are conveniently numbered 0 through M1. Doge i initially resides in skyscraper Bi. Doge i has a mystical power, represented with a positive integer Pi. This mystical power enables doges to jump between skyscrapers. In a single jump, a doge with superpower p that is currently in skyscraper b can move to either skyscraper b+p (if 0b+p<N) or skyscraper bp (if 0bp<N).

Doge 0 is the most awesome doge, and it is the leader of all the doges. It has an urgent news for doge 1, and wants the news to reach doge 1 as quickly as possible. Any doge that has received the news can do any of the following actions:

  • Make a jump to move to some other skyscraper.
  • Pass the news to another doge in the same skyscraper.

Please help the doges by calculating the minimum number of total jumps required by all doges to pass the news to doge 1, or if it is impossible to do so.

Input Specification

The first line contains two integers N and M. Each of the next M lines contains two integers Bi and Pi.

Output Specification

A single line containing the minimum number of total jumps, or -1 if it is impossible.

Sample Input

Copy
5 3
0 2
1 1
4 1

Sample Output

Copy
5

Explanation for Sample Output

Here is one of the possible scenarios to pass the news using 5 jumps:

  • Doge 0 jumps to skyscraper 2 and then to skyscraper 4 (2 jumps).
  • Doge 0 passes the news to doge 2.
  • Doge 2 jumps to skyscraper 3, and then to skyscraper 2, and then to skyscraper 1 (3 jumps).
  • Doge 2 passes the news to doge 1.

Subtasks

For each subtask,

  • 0Bi<N
Subtask 1 (10 points)
  • 1N10
  • 1Pi10
  • 2M3
Subtask 2 (12 points)
  • 1N100
  • 1Pi100
  • 2M2000
Subtask 3 (14 points)
  • 1N2000
  • 1Pi2000
  • 2M2000
Subtask 4 (21 points)
  • 1N2000
  • 1Pi2000
  • 2M30000
Subtask 5 (43 points)
  • 1N30000
  • 1Pi30000
  • 2M30000

Comments

There are no comments at the moment.