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<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 201, M = 50001;
const int INF = 1e15;
int n, m;
multiset<pair<int, int>> adj[N];
int c[M], d[M];
pair<int, int> edges[M];
vector<int> dijkstra(int source){
vector<int> dist(n + 1, INF);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, source});
dist[source] = 0;
while (!pq.empty()) {
int u = pq.top().second;
int du = pq.top().first;
pq.pop();
if (du > dist[u]) continue; // Skip if this node is already processed
for (auto &n : adj[u]){
int v = n.first;
int uv_weight = c[n.second];
if (dist[v] > du + uv_weight){
dist[v] = du + uv_weight;
pq.push({dist[v], v});
}
}
}
return dist;
}
signed main(){
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
adj[i].clear();
}
vector<vector<int>> dist(n + 1, vector<int>(n + 1, INF));
for (int i = 1; i <= n; ++i) {
dist[i][i] = 0;
}
for (int i = 0; i < m; ++i){
int u, v;
cin >> u >> v >> c[i] >> d[i];
adj[u].insert({v, i});
edges[i] = {u, v};
dist[u][v] = min(dist[u][v], c[i]);
}
// Floyd Warshall
for (int k = 1; k <= n; ++k) {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
int ans = min(INF, dist[1][n] + dist[n][1]);
for (int i = 0; i < m; ++i) {
int u = edges[i].first, v = edges[i].second;
if (min(dist[1][n], dist[1][v] + c[i] + dist[u][n]) +
min(dist[n][1], dist[n][v] + c[i] + dist[u][1]) + d[i] < ans) {
adj[u].erase(adj[u].find({v, i}));
adj[v].insert({u, i});
vector<int> from_start = dijkstra(1);
vector<int> to_end = dijkstra(n);
ans = min(ans, d[i] + from_start[n] + to_end[1]);
adj[v].erase(adj[v].find({edges[i].first, i}));
adj[u].insert({v, i});
}
}
if (ans == INF) {
ans = -1;
}
cout << ans;
}
# | 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... |