Minimum cost

3

43 votes
Algorithms, Breadth First Search, Easy, Graphs
Problem

You are standing at position 1. From position i, you can walk to i+1 or i1 with cost 1. From position i, you can travel to without any cost to pi (p is a permutation of numbers 1n). You have to reach position n. Determine the minimum possible cost.

Input format

  • First line: T denotes the number of test cases (1T10)
  • For each test case:
    • First line: n (1n50 000)
    • Second line: n integers where the ith integer is pi
      Note: It is guaranteed that p is a permutation.

Output format
Print the minimum possible cost.

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

-

Editor Image

?