#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1e18;
struct Edge {
int to, c;
ll p;
};
map<int, vector<Edge>> graph[100001];
ll dp[100001]; // dp[u] = chi phí tối thiểu để đến u (trạng thái bình thường)
map<int, ll> dp2[100001]; // dp2[u][c] = chi phí nếu đến u trong trạng thái "đang treo màu c"
map<int, ll> psum[100001]; // psum[u][c] = tổng trọng số các cạnh màu c gắn với u
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v, c;
ll p;
cin >> u >> v >> c >> p;
graph[u][c].push_back({v, c, p});
graph[v][c].push_back({u, c, p});
psum[u][c] += p;
psum[v][c] += p;
}
fill(dp, dp + n + 1, INF);
dp[1] = 0;
using State = tuple<ll,int,int>;
// (chi phí, node, màu đang treo; màu=0 nếu trạng thái thường)
priority_queue<State, vector<State>, greater<State>> pq;
pq.push({0, 1, 0});
while (!pq.empty()) {
auto [cost, node, c] = pq.top();
pq.pop();
if (c != 0) {
if (dp2[node][c] != cost) continue;
for (auto e : graph[node][c]) {
ll newCost = cost + (psum[node][c] - e.p);
if (newCost < dp[e.to]) {
dp[e.to] = newCost;
pq.push({newCost, e.to, 0});
}
}
} else {
if (dp[node] != cost) continue;
for (auto &kv : graph[node]) {
int col = kv.first;
for (auto e : kv.second) {
ll case1 = cost + psum[node][col] - e.p;
if (case1 < dp[e.to]) {
dp[e.to] = case1;
pq.push({case1, e.to, 0});
}
ll case2 = cost + e.p;
if (case2 < dp[e.to]) {
dp[e.to] = case2;
pq.push({case2, e.to, 0});
}
ll case3 = cost;
if (!dp2[e.to].count(col) || case3 < dp2[e.to][col]) {
dp2[e.to][col] = case3;
pq.push({case3, e.to, col});
}
}
}
}
}
cout << (dp[n] >= INF ? -1 : dp[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... |