#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define ld long double
using namespace std;
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
const int NMAX = 1e5;
const ll INF = 1e18;
struct Edge {
int to, c, p;
Edge(int to, int c, int p) : to(to), c(c), p(p) {}
};
struct PQElement {
int node, c;
ll cost;
bool operator < (const PQElement &other) const {
return other.cost < cost;
}
};
int n, m;
vector<Edge> g[NMAX + 1];
ll dp[NMAX + 1];
map<int, ll> sum[NMAX + 1];
map<int, ll> dp1[NMAX + 1];
void Dijkstra() {
for(int i = 1; i <= n; i++) {
dp[i] = INF;
}
priority_queue<PQElement> pq;
pq.push({1, 0, 0});
while(!pq.empty()) {
auto [node, c, cost] = pq.top();
pq.pop();
// cout << node << ' ' << c << ' ' << cost << '\n';
if(!c) {
if(dp[node] != INF) {
continue;
}
dp[node] = cost;
for(auto [next_node, edge_c, p] : g[node]) {
// I change the colour of the edge
pq.push({next_node, 0, cost + p});
// I change every edge that has this edge colour
pq.push({next_node, 0, cost + (sum[node][edge_c] - p)});
// I change the colour of the edge and all of the same-coloured edges of next_node with this colour
// I compute this when I am at next_node
pq.push({next_node, edge_c, cost});
}
}
else {
if(dp1[node].count(c)) {
continue;
}
dp1[node][c] = cost;
for(auto [next_node, edge_c, p] : g[node]) {
if(edge_c != c) {
continue;
}
// I can only change every edge that has this edge colour
pq.push({next_node, 0, cost + (sum[node][c] - p)});
}
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= m; i++) {
int a, b, c, p;
cin >> a >> b >> c >> p;
g[a].emplace_back(b, c, p);
g[b].emplace_back(a, c, p);
sum[a][c] += p;
sum[b][c] += p;
}
// for(auto [a, b, c] : g[1]) {
// cout << a << ' ' << b << ' ' << c << '\n';
// }
Dijkstra();
// for(int i = 1; i <= n; i++) {
// cout << dp[i] << '\n';
// }
// cout << '\n';
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... |