1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include <iostream> #include <vector> #include <queue> #include <algorithm>
using namespace std;
const int INF = 1e9;
struct Edge { int to, weight; };
vector<int> dijkstra(int n, vector<vector<Edge>> &graph, int start) { vector<int> distances(n + 1, INF); distances[start] = 0; priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; pq.push({0, start});
while (!pq.empty()) { int current_distance = pq.top().first; int current_node = pq.top().second; pq.pop();
if (current_distance > distances[current_node]) { continue; }
for (const auto &edge : graph[current_node]) { int neighbor = edge.to; int weight = edge.weight; int distance = current_distance + weight;
if (distance < distances[neighbor]) { distances[neighbor] = distance; pq.push({distance, neighbor}); } } }
return distances; }
void find_best_drop_off(int n, int m, int a, int b, vector<vector<Edge>> &graph) { vector<int> distances_from_1 = dijkstra(n, graph, 1); vector<int> distances_from_a = dijkstra(n, graph, a); vector<int> distances_from_b = dijkstra(n, graph, b);
int min_distance = INF; vector<pair<int, int>> results;
for (int i = 1; i <= n; ++i) { if (distances_from_1[i] + distances_from_a[i] == distances_from_1[a]) { if (distances_from_b[i] < min_distance) { min_distance = distances_from_b[i]; results = {{i, distances_from_1[i]}}; } else if (distances_from_b[i] == min_distance) { results.push_back({i, distances_from_1[i]}); } } }
sort(results.begin(), results.end(), [](const pair<int, int> &a, const pair<int, int> &b) { return a.second != b.second ? a.second < b.second : a.first < b.first; });
cout << min_distance << endl; for (const auto &result : results) { cout << result.first << " " << result.second << endl; } }
int main() { int n, m, a, b; cin >> n >> m >> a >> b;
vector<vector<Edge>> graph(n + 1); for (int i = 0; i < m; ++i) { int u, v, w; cin >> u >> v >> w; graph[u].push_back({v, w}); graph[v].push_back({u, w}); }
find_best_drop_off(n, m, a, b, graph);
return 0; }
|