CodeForces-1340C.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main() {
  4. ios::sync_with_stdio(false);
  5. cin.tie(nullptr);
  6. int road_length, m;
  7. cin >> road_length >> m;
  8. vector<int> position(m);
  9. for (int &x : position) cin >> x;
  10. sort(position.begin(), position.end());
  11. int green, red;
  12. cin >> green >> red;
  13. const int INF = numeric_limits<int>::max() / 4;
  14. vector<int> distance(m * green, INF);
  15. auto id = [green](int island, int spent) { return island * green + spent; };
  16. int start = lower_bound(position.begin(), position.end(), 0) - position.begin();
  17. deque<pair<int, int>> queue;
  18. distance[id(start, 0)] = 0;
  19. queue.push_back({start, 0});
  20. long long answer = numeric_limits<long long>::max();
  21. while (!queue.empty()) {
  22. auto [island, spent] = queue.front();
  23. queue.pop_front();
  24. int completed = distance[id(island, spent)];
  25. int to_finish = road_length - position[island];
  26. if (to_finish <= green - spent) {
  27. answer = min(answer, 1LL * completed * (green + red) + spent + to_finish);
  28. }
  29. for (int direction : {-1, 1}) {
  30. int next_island = island + direction;
  31. if (next_island < 0 || next_island >= m) continue;
  32. int next_spent = spent + abs(position[next_island] - position[island]);
  33. if (next_spent > green) continue;
  34. int add = (next_spent == green);
  35. if (add) next_spent = 0;
  36. int state = id(next_island, next_spent);
  37. if (completed + add >= distance[state]) continue;
  38. distance[state] = completed + add;
  39. if (add) queue.push_back({next_island, next_spent});
  40. else queue.push_front({next_island, next_spent});
  41. }
  42. }
  43. if (answer == numeric_limits<long long>::max()) cout << -1 << '\n';
  44. else cout << answer << '\n';
  45. return 0;
  46. }