ceva_megamind

Глеб и электрокар

Jan 14th, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <set>
  5. #include <queue>
  6.  
  7. using namespace std;
  8.  
  9. int main()
  10. {
  11.  
  12.     ios_base::sync_with_stdio(false);
  13.     cin.tie(0);
  14.     cout.tie(0);
  15.     //просто считываем всё
  16.     int k, n, m, u, v, p, q, r;
  17.     cin >> k >> n >> m >> u >> v;
  18.     vector < vector < pair<int, int> > > g(n + 1);
  19.     for (int i = 0; i < m; ++i) {
  20.         cin >> p >> q >> r;
  21.         g[p].push_back({ q,r });
  22.         g[q].push_back({ p,r });
  23.     }
  24.     int l, x;
  25.     set<int>s;
  26.     cin >> l;
  27.     for (int i = 0; i < l; i++) {
  28.         cin >> x;
  29.         s.insert(x);
  30.     }
  31.  
  32.     //dp[i][j]-мин. кол-во заправок, чтоб доехать до города i с бензином j
  33.     const long long INF = 1e18;
  34.     vector <vector<long long>> dp(n + 1, vector<long long>(k + 1, INF));
  35.     dp[u][k] = 0;
  36.     vector <bool> used(n + 1);
  37.     used[u] = true;
  38.     queue <int> qu;
  39.     qu.push(u);
  40.     while (!qu.empty()) {
  41.         u = qu.front();
  42.         qu.pop();
  43.         for (auto i = g[u].begin(); i != g[u].end(); i++) {
  44.             int len = (*i).second;
  45.             int versh = (*i).first;
  46.             for (int j = 0; j <= k; j++) {
  47.                 if (dp[u][j] != INF) {
  48.                     if (j - len >= 0) { //хватает бензина, чтоб доехать
  49.                         dp[versh][j - len] = min(dp[versh][j - len], dp[u][j]);
  50.                         if (!used[versh]) {
  51.                             qu.push(versh);
  52.                             used[versh] = true;
  53.                         }
  54.                     }
  55.                     if (s.find(u) != s.end()) { //u-заправка
  56.                         if (k - len >= 0) {
  57.                             if (dp[u][j] + 1 < dp[versh][k - len]) {
  58.                                 dp[versh][k - len] = dp[u][j] + 1;
  59.                                 qu.push(versh);
  60.                                 used[versh] = true;
  61.                             }
  62.                         }
  63.                     }
  64.                 }
  65.             }
  66.         }
  67.     }
  68.     //ответ - минимальный из dp[v] с любым бензином
  69.     auto ans = min_element(dp[v].begin(), dp[v].end());
  70.     if (*ans == INF)
  71.         cout << -1;
  72.     else
  73.         cout << *ans;
  74. }
Add Comment
Please, Sign In to add comment