#include "bits/stdc++.h"
using namespace std;
#define int long long
const int INF = 1e18;
int n, m, s, t, u, v;
vector<pair<int, int>> graph[100005];
// Standard Dijkstra to compute shortest distances from a source
vector<int> dijkstra(int src) {
vector<int> dist(n + 1, INF);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
dist[src] = 0;
pq.push({0, src});
while (!pq.empty()) {
int d = pq.top().first;
int node = pq.top().second;
pq.pop();
if (d > dist[node]) continue;
for (auto [next, weight] : graph[node]) {
if (dist[node] + weight < dist[next]) {
dist[next] = dist[node] + weight;
pq.push({dist[next], next});
}
}
}
return dist;
}
// Modified Dijkstra for U to V considering S-T shortest paths
int dijkstra_uv_with_pass(vector<int>& dist_s, vector<int>& dist_t) {
vector<int> dist(n + 1, INF);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
dist[u] = 0;
pq.push({0, u});
while (!pq.empty()) {
int d = pq.top().first;
int node = pq.top().second;
pq.pop();
if (d > dist[node]) continue;
for (auto [next, weight] : graph[node]) {
// Check if this edge can be on some S-T shortest path
bool is_free = (dist_s[node] + weight + dist_t[next] == dist_s[t]) ||
(dist_s[next] + weight + dist_t[node] == dist_s[t]);
int cost = is_free ? 0 : weight;
if (dist[node] + cost < dist[next]) {
dist[next] = dist[node] + cost;
pq.push({dist[next], next});
}
}
}
return dist[v];
}
int solve() {
// Compute shortest distances from S and T
vector<int> dist_s = dijkstra(s);
vector<int> dist_t = dijkstra(t);
if (dist_s[t] == INF) return -1; // No path from S to T (shouldn't happen per constraints)
// Compute minimum cost from U to V considering the commuter pass
return dijkstra_uv_with_pass(dist_s, dist_t);
}
signed main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> m;
cin >> s >> t >> u >> v;
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
graph[a].push_back({b, c});
graph[b].push_back({a, c});
}
cout << solve() << endl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |