#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
typedef long long ll;
using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
struct Edge {
ll a, b, c, d;
};
ll M = 201, inf=1e18;
ll n, m;
vector<vector<ll>> g(M), gt(M), D(M, vector<ll>(M, inf)), C(M, vector<ll>(M, inf)), used(2, vector<ll>(50'001));
vector<Edge> e;
ll dijkstra1(ll s, ll z) {
ll koniec = (z ? 1 : n);
vector<ll> dist(M, inf), par(M, -1);
vector<ll> vis(M, 0);
dist[s] = 0;
for(int i=0; i<n; ++i) {
int v = 0;
for(int x=1; x<=n; ++x) {
if(!vis[x] && dist[x] < dist[v]) v = x;
}
if(dist[v] == inf) break;
vis[v] = 1;
for(auto k : g[v]) {
int u = e[k].b;
if(dist[v] + e[k].c < dist[u]) {
dist[u] = dist[v] + e[k].c;
if(par[u]!=-1) used[z][par[u]] = 0;
used[z][k] = 1;
par[u] = k;
}
}
}
return dist[koniec];
}
ll dijkstra2(ll s, ll koniec, ll z) {
vector<ll> dist(M, inf);
vector<ll> vis(M, 0);
dist[s] = 0;
for(int i=0; i<n; ++i) {
int v = 0;
for(int x=1; x<=n; ++x) {
if(!vis[x] && dist[x] < dist[v]) v = x;
}
if(dist[v] == inf) break;
vis[v] = 1;
for(auto k : g[v]) {
if(k==z) continue;
int u = e[k].b;
if(dist[v] + e[k].c < dist[u]) dist[u] = dist[v] + e[k].c;
}
for(auto k : gt[v]) {
if(k!=z) continue;
int u = e[k].a;
if(dist[v] + e[k].c < dist[u]) dist[u] = dist[v] + e[k].c;
}
}
return dist[koniec];
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for(int i=1; i<=n; ++i) D[i][i] = 0;
for(int i=0; i<m; ++i) {
ll a, b, c, d;
cin >> a >> b >> c >> d;
e.push_back({a, b, c, d});
D[a][b] = min(D[a][b], c);
g[a].push_back(i);
gt[b].push_back(i);
}
for(int k=1; k<=n; ++k) for(int i=1; i<=n; ++i) for(int j=1; j<=n; ++j) D[i][j] = min(D[i][j], D[i][k] + D[k][j]);
for(int i=1; i<=n; ++i) for(int j=1; j<=n; ++j) C[i][j] = (D[i][j]<inf);
ll v0 = dijkstra1(1, 0);
ll v1 = dijkstra1(n, 1);
ll ans = inf;
for(auto[a,b,c,d] : e) {
ans = min(ans, D[1][b] + D[a][n] + D[n][b] + D[a][1] + 2*c + d);
}
if(C[1][n]) {
for(int i=0; i<m; ++i) {
auto[a,b,c,d] = e[i];
if(used[0][i]) {
ans = min(ans, D[n][b] + c + d + D[a][1] + dijkstra2(1, n, i));
} else {
ans = min(ans, D[n][b] + c + d + D[a][1] + v0);
}
}
}
if(C[n][1]) {
for(int i=0; i<m; ++i) {
auto[a,b,c,d] = e[i];
if(used[1][i]) {
ans = min(ans, D[1][b] + c + d + D[a][n] + dijkstra2(n, 1, i));
} else {
ans = min(ans, D[1][b] + c + d + D[a][n] + v1);
}
}
}
if(ans < inf) cout << ans << "\n";
else cout << "-1\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... |