This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <algorithm>
#include <array>
#include <iostream>
#include <queue>
#include <vector>
int main() {
int n, m;
std::cin >> n >> m;
constexpr int kInf = 1'000'000'000;
std::vector<std::vector<int>> dist(n, std::vector<int>(n, kInf));
for (int i = 0; i < n; ++i) dist[i][i] = 0;
std::vector<std::array<int, 4>> ed(m);
std::vector<std::vector<std::pair<int, int>>> g(n);
for (int i = 0; i < m; ++i) {
int u, v, c, d;
std::cin >> u >> v >> c >> d;
u--, v--;
dist[u][v] = std::min(dist[u][v], c);
ed[i] = {u, v, c, d};
g[u].emplace_back(v, i);
}
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
dist[i][j] = std::min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
int ans = dist[0][n - 1] + dist[n - 1][0];
auto Dijkstra = [&](int s, int e, int v) {
std::vector<int> dist(n, kInf), used(n);
std::priority_queue<std::pair<int, int>> pq;
pq.emplace(0, s);
dist[s] = 0;
while (!pq.empty()) {
int x = pq.top().second;
pq.pop();
if (x == e) break;
if (used[x]++) continue;
for (auto i : g[x]) {
int u = i.first, z = i.second;
if (z == v) continue;
if (dist[u] > dist[x] + ed[z][2]) {
dist[u] = dist[x] + ed[z][2];
pq.emplace(-dist[u], u);
}
}
if (x == ed[v][1]) {
if (dist[ed[v][0]] > dist[x] + ed[v][2]) {
dist[ed[v][0]] = dist[x] + ed[v][2];
pq.emplace(-dist[ed[v][0]], ed[v][0]);
}
}
}
return dist[e];
};
for (int i = 0; i < m; ++i) {
int u = ed[i][0], v = ed[i][1], c = ed[i][2], d = ed[i][3];
int a = std::min(dist[0][n - 1], dist[0][v] + dist[u][n - 1] + c);
int b = std::min(dist[n - 1][0], dist[n - 1][v] + dist[u][0] + c);
if (a + b + d < ans) {
int x = Dijkstra(0, n - 1, i);
int y = Dijkstra(n - 1, 0, i);
ans = std::min(ans, x + y + d);
}
}
if (ans >= kInf) ans = -1;
std::cout << ans << "\n";
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... |