Untitled

 avatar
unknown
c_cpp
a year ago
1.6 kB
3
Indexable
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 1005;
const int INF = 2e9;
int n, V;
vector<int> graph[maxn];
struct node {
    int idx, cost;
    node () {}
    node(int _idx, int _cost) {
        idx = _idx;
        cost = _cost;
    }
    bool operator < (const node &tmp) const {
        return cost > tmp.cost;
    }
};
int main()
{
    ios_base::sync_with_stdio(false);
    cin >> n >> V;
    vector<int> v(n);
    for(int i = 0; i < n; i++) {
        cin >> v[i];
        graph[v[i]].push_back(i);
    }
    priority_queue<node> pq;
    vector<bool> visited(n + 1, false);
    vector<bool> portal(n + 1, false);
    vector<int> dist(n + 1, INF);
    dist[0] = 0;
    pq.push(node(0, 0));
    while(!pq.empty()) {
        node c = pq.top();
        pq.pop();
        
        if(c.idx == n - 1) {
            cout << c.cost << endl;
            break;
        }
        if(visited[c.idx]) continue;
        visited[c.idx] = true;
        
        if(c.idx > 0) {
            pq.push(node(c.idx - 1, c.cost + 1));
        }
        if(c.idx + 1 < n) {
            pq.push(node(c.idx + 1, c.cost + 1));
        }
        
        if(!portal[v[c.idx]]) {
            for(int i = 0; i < (int) graph[v[c.idx]].size(); i++) {
                int pos = graph[v[c.idx]][i];
                if(!visited[pos] and c.cost + V < dist[pos]) {
                    pq.push(node(pos, c.cost + V));
                    dist[pos] = c.cost + V;
                }
           }
            portal[v[c.idx]] = true;
        }
    }
    return 0;
}


Editor is loading...
Leave a Comment