#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define len(v) (int)((v).size())
const int inf = 1e9;
const int sz = 1 << 20;
int tree[sz];
void init(int v, int l, int r){
tree[v] = 0;
if (r - l == 1) return;
int m = (l + r) / 2;
init(v * 2, l, m);
init(v * 2 + 1, m, r);
}
void upd(int v, int l, int r, int qi){
tree[v] += 1;
if (r - l == 1){
return;
}
int m = (l + r) / 2;
if (qi < m) upd(v * 2, l, m, qi);
else upd(v * 2 + 1, m, r, qi);
}
int sum(int v, int l, int r, int ql, int qr){
if (l >= qr || ql >= r) return 0;
if (l >= ql && r <= qr) return tree[v];
int m = (l + r) / 2;
int r1 = sum(v * 2, l, m, ql, qr);
int r2 = sum(v * 2 + 1, m, r, ql, qr);
return r1 + r2;
}
struct edge{
int to, cl, w;
edge(int to, int cl, int w) : to(to), cl(cl), w(w) {};
};
bool operator<(edge a, edge b){
if (a.w != b.w) return a.w < b.w;
if (a.to != b.to) return a.to < b.to;
return a.cl < b.cl;
}
inline void solve(){
int n, m;
cin >> n >> m;
vector<vector<edge>> g(n);
vector<map<int, int>> cnt(n);
vector<map<int, ll>> cnt2(n);
for (int i = 0; i < m; ++i){
int a, b, c, p;
cin >> a >> b >> c >> p;
--a, --b, --c;
cnt[a][c]++;
cnt[b][c]++;
cnt2[a][c] += p;
cnt2[b][c] += p;
g[a].emplace_back(b, c, p);
g[b].emplace_back(a, c, p);
}
vector<map<pair<int, int>, ll>> d(n);
for (int i = 0; i < n; ++i){
for (edge u : g[i]){
d[i][{u.cl, u.w}] = inf;
d[i][{u.cl, 0}] = inf;
}
}
set<pair<ll, edge>> q;
for (int i = 0; i < m; ++i){
d[0][{i, 0}] = 0;
q.insert({0, edge(0, i, 0)});
}
while (!q.empty()){
int v = q.begin()->second.to;
int c = q.begin()->second.cl;
int qw = q.begin()->second.w;
q.erase(q.begin());
for (edge u : g[v]){
ll w = cnt2[v][u.cl] - u.w + d[v][{c, qw}];
if (u.cl == c) w -= qw;
if ((u.cl != c || qw > 0) && d[u.to][{u.cl, 0}] > w){
pair<ll, edge> obj = {d[u.to][{u.cl, 0}], edge(u.to, u.cl, 0)};
if (q.find(obj) != q.end()){
q.erase(obj);
}
d[u.to][{u.cl, 0}] = w;
q.insert(obj);
}
w = d[v][{c, qw}] + u.w;
if (d[u.to][{u.cl, u.w}] > w){
pair<ll, edge> obj = {d[u.to][{u.cl, u.w}], u};
if (q.find(obj) != q.end()){
q.erase(obj);
}
d[u.to][{u.cl, u.w}] = w;
q.insert(obj);
}
}
}
/*
for (int i = 0; i < n; ++i){
for (pair<pair<int, int>, ll> p : d[n - 1]){
cout << "v = " << i << " c = " << p.first.first << " w = " << p.first.second << " d = " << p.second << '\n';
}
}
*/
ll ans = inf;
for (pair<pair<int, int>, ll> p : d[n - 1]){
ans = min(ans, p.second);
}
if (ans >= inf){
cout << "-1\n";
}
else{
cout << ans << '\n';
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cout.precision(60);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |