#include #include #include #include using namespace std; const int maxn = 1e5 + 10; const int INF = 2e9; vector> graph[maxn]; struct node { int idx, shortest_path; node() {} node(int _idx, int _shortest_path) { idx = _idx; shortest_path = _shortest_path; } bool operator < (const node & tmp) const { return shortest_path > tmp.shortest_path; } }; int main(){ int n, v; cin >> n >> v; vector portal(n); for(int i = 0; i < n; i++) { cin >> portal[i]; } vector visited(n, false); vector portal_visited(n, false); vector dist(n, INF); priority_queue pq; pq.push(node(0, 0)); dist[0] = 0; while(!pq.empty()) { node c = pq.top(); pq.pop(); if(c.idx == n - 1) { cout << c.shortest_path << endl; break; } if(visited[c.idx]) continue; visited[c.idx] = true; if(c.idx + 1 < n) { pq.push(node(c.idx + 1, c.shortest_path + 1)); } if(c.idx - 1 >= 0) { pq.push(node(c.idx - 1, c.shortest_path + 1)); } if(!portal_visited[portal[c.idx]]) { for(int i = 0; i < n; i++) { if(portal[i] == portal[c.idx]) { pq.push(node(i, c.shortest_path + v)); } } portal_visited[portal[c.idx]] = true; } } return 0; }