#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
typedef long long ll;
using namespace std;
struct edge {
int to, color, cost;
edge(){}
edge(int a, int b, int c) {
to = a;
color = b;
cost = c;
}
};
const ll INF = 1e18;
vector<vector<edge>> adj;
vector<ll> dist, sum, best;
int n, m;
ll dijkstra() {
dist[1] = 0;
priority_queue<pair<ll, int>> pq;
pq.push({0, 1});
while (pq.size()) {
int u = pq.top().second;
ll curr = -pq.top().first;
pq.pop();
if (curr != dist[u]) continue;
for (edge &e : adj[u]) {
sum[e.color] += e.cost;
best[e.color] = min(best[e.color], dist[e.to]);
}
for (edge e : adj[u]) {
int to = e.to;
int color = e.color;
int w = e.cost;
ll tmp = min(0LL + w, sum[color] - w);
if (dist[to] > curr + tmp) {
dist[to] = curr + tmp;
pq.push({-dist[to], to});
}
if (dist[to] > best[color] + sum[color] - w) {
dist[to] = best[color] + sum[color] - w;
pq.push({-dist[to], to});
}
}
for (edge e : adj[u]) {
sum[e.color] = 0;
best[e.color] = INF;
}
}
if (dist[n] == INF) dist[n] = -1;
return dist[n];
}
int main() {
cin.tie(0) -> sync_with_stdio(0);
cin >> n >> m;
adj.resize(n + 1);
dist.resize(2 * n + 1);
sum.resize(m + 1);
best.resize(m + 1);
for (int i = 1; i<=m; ++i) {
int u, v, color, cost;
cin >> u >> v >> color >> cost;
edge a = edge(v, color, cost);
edge b = edge(u, color, cost);
adj[u].push_back(a);
adj[v].push_back(b);
}
for (int i = 1; i<=n; ++i) dist[i] = INF;
for (int i = 1; i<=m; ++i) best[i] = INF;
cout << dijkstra() << '\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... |