No.1995 CHIKA Road
タグ : / 解いたユーザー数 148
作問者 :
MasKoaTS
/ テスター :
Problem Statement
Koume City has $N$ towns numbered $1, 2, \dots, N$,
which are connected one-way by the $(N - 1)$ "underground roads" and $M$ "shortcuts" described below.
The $i$-th $(1 \leq i \leq N - 1)$ "underground road" connects town $i$ and town $(i + 1)$ in this order, and the distance between them is $2$.
The $j$-th $(1 \leq j \leq M)$ "shortcut" connects town $A_{j}$ and town $B_{j}$ $(A_{j} < B_{j})$ in this order, and the distance between them is $(2 B_{j} - 2 A_{j} - 1)$.
Find the shortest distance to travel from town $1$ to town $N$ using only these $(N + M - 1)$ roads.
Constraints
$2 \leq N \leq 10^{9}$
$\displaystyle 1 \leq M \leq \min \left( 10^{5}, \frac{ N \times (N - 1) }{ 2 } \right)$
$1 \leq A_{i} < B_{i} \leq N$ $(1 \leq i \leq M)$
$( A_{i}, B_{i} ) \neq ( A_{j}, B_{j} )$ $(1 \leq i < j \leq M)$
All inputs are integers.
Input
The input is given in the following format.
$N$ $M$
$A_{1}$ $B_{1}$
$A_{2}$ $B_{2}$
$\vdots$
$A_{M}$ $B_{M}$
The $1$st line contains $N$ and $M$ in this order, separated by a space.
The $(1 + i)$-th $(1 \leq i \leq M)$ line contains $A_{i}$ and $B_{i}$ in this order, separated by a space.
Output
Output the answer on $1$ line, followed by a newline.
Sample
Sample 1
Input
10 5 1 6 2 4 2 7 4 6 6 9
Output
15
To travel from town $1$ to town $10$ with the shortest distance, consider the following route.
Move from town $1$ to town $2$ via an "underground road"
Move from town $2$ to town $4$ via a "shortcut"
Move from town $4$ to town $6$ via a "shortcut"
Move from town $6$ to town $9$ via a "shortcut"
Move from town $9$ to town $10$ via an "underground road"
Therefore, the shortest distance to be found is
$2 + (2 \times 4 - 2 \times 2 - 1) + (2 \times 6 - 2 \times 4 - 1) + (2 \times 9 - 2 \times 6 - 1) + 2 = 15$
.
Sample 2
Input
2 1 1 2
Output
1
Note that there are $2$ roads connecting town $1$ and town $2$ in this order, and they are distinct: one is an "underground road" and the other is a "shortcut".
Sample 3
Input
1000000000 7 1 2 7 8 3 4 6 7 4 5 5 6 2 3
Output
1999999991
提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。