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 N-1 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 M-1. Doge i initially resides in skyscraper B_i. Doge i has a mystical power, represented with a positive integer P_i. 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 0 \le b+p < N) or skyscraper b-p (if 0 \le b-p < 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 B_i and P_i.

Output Specification

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

Sample Input

5 3
0 2
1 1
4 1

Sample Output

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,

  • 0 \le B_i < N
Subtask 1 (10 points)
  • 1 \le N \le 10
  • 1 \le P_i \le 10
  • 2 \le M \le 3
Subtask 2 (12 points)
  • 1 \le N \le 100
  • 1 \le P_i \le 100
  • 2 \le M \le 2\,000
Subtask 3 (14 points)
  • 1 \le N \le 2\,000
  • 1 \le P_i \le 2\,000
  • 2 \le M \le 2\,000
Subtask 4 (21 points)
  • 1 \le N \le 2\,000
  • 1 \le P_i \le 2\,000
  • 2 \le M \le 30\,000
Subtask 5 (43 points)
  • 1 \le N \le 30\,000
  • 1 \le P_i \le 30\,000
  • 2 \le M \le 30\,000

Comments

There are no comments at the moment.