Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <set>
- #include <queue>
- using namespace std;
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin.tie(0);
- cout.tie(0);
- //просто считываем всё
- int k, n, m, u, v, p, q, r;
- cin >> k >> n >> m >> u >> v;
- vector < vector < pair<int, int> > > g(n + 1);
- for (int i = 0; i < m; ++i) {
- cin >> p >> q >> r;
- g[p].push_back({ q,r });
- g[q].push_back({ p,r });
- }
- int l, x;
- set<int>s;
- cin >> l;
- for (int i = 0; i < l; i++) {
- cin >> x;
- s.insert(x);
- }
- //dp[i][j]-мин. кол-во заправок, чтоб доехать до города i с бензином j
- const long long INF = 1e18;
- vector <vector<long long>> dp(n + 1, vector<long long>(k + 1, INF));
- dp[u][k] = 0;
- vector <bool> used(n + 1);
- used[u] = true;
- queue <int> qu;
- qu.push(u);
- while (!qu.empty()) {
- u = qu.front();
- qu.pop();
- for (auto i = g[u].begin(); i != g[u].end(); i++) {
- int len = (*i).second;
- int versh = (*i).first;
- for (int j = 0; j <= k; j++) {
- if (dp[u][j] != INF) {
- if (j - len >= 0) { //хватает бензина, чтоб доехать
- dp[versh][j - len] = min(dp[versh][j - len], dp[u][j]);
- if (!used[versh]) {
- qu.push(versh);
- used[versh] = true;
- }
- }
- if (s.find(u) != s.end()) { //u-заправка
- if (k - len >= 0) {
- if (dp[u][j] + 1 < dp[versh][k - len]) {
- dp[versh][k - len] = dp[u][j] + 1;
- qu.push(versh);
- used[versh] = true;
- }
- }
- }
- }
- }
- }
- }
- //ответ - минимальный из dp[v] с любым бензином
- auto ans = min_element(dp[v].begin(), dp[v].end());
- if (*ans == INF)
- cout << -1;
- else
- cout << *ans;
- }
Add Comment
Please, Sign In to add comment