Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Subsequence Path

#include <bits/stdc++.h>
using namespace std;

const long long inf = 1e15;

void solve() {
    int n, m, k;
    cin >> n >> m >> k;

    vector<int> a(m), b(m), c(m);
    for (int i = 0; i < m; i++) {
        cin >> a[i] >> b[i] >> c[i];
        a[i]--, b[i]--;
    }

    // dp[i] is the minimum distance of node i from src when we only traverse
    // the edges which form a subsequence so far.
    vector<long long> dp(n, inf);
    dp[0] = 0;
    for (int i = 0; i < k; i++) {
        int idx;
        cin >> idx;
        idx--;
        int u = a[idx];
        int v = b[idx];

        // Relax the edge (u, v).
        dp[v] = min(dp[v], dp[u] + c[idx]);
    }

    if (dp[n - 1] < inf) {
        cout << dp[n - 1] << "\n";
    } else {
        cout << -1 << "\n";
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    solve();
    return 0;
}