/*#pragma GCC optimize("O3")
#pragma GCC optimization("Ofast,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")*/
#include <bits/stdc++.h>
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>*/
#define ll long long
#define ll1 long long
#define ull unsigned long long
#define dou long double
#define str string
#define vll vector<ll>
#define vi vector<int>
#define pll pair<ll, ll>
#define vpll vector<pll>
#define vbool vector<bool>
#define vstr vector<str>
#define vvll vector<vll>
#define pb push_back
#define pf push_front
#define endl "\n"
#define fr first
#define se second
// #define sortcmp(a) sort(a.begin(), a.end(), cmp)
#define sort(a) sort(a.begin(), a.end())
#define reverse(a) reverse(a.begin(), a.end())
#define speed ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define INF 1000000000000000007
#define ordered_set tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update>
using namespace std;
//using namespace __gnu_pbds;
mt19937 rng(time(0));
ll randll(ll l, ll r) {
return uniform_int_distribution<ll>(l, r)(rng);
}
struct ed {
ll v, c, d;
bool operator< (const ed& ot) const {
if (v != ot.v) return v < ot.v;
if (c != ot.c) return c < ot.c;
return d < ot.d;
}
};
int main(){
speed;
srand(time(0));
ll n, m;
cin >> n >> m;
vector<vector<ed>> g(n+7);
vector<map<ll, vpll>> gc(n+7);
for (int i = 0; i < m; i ++) {
ll a, b, c, d;
cin >> a >> b >> c >> d;
g[a].pb({b, c, d});
gc[a][c].pb({b, d});
g[b].pb({a, c, d});
gc[b][c].pb({a, d});
}
vector<map<ll, ll>> sm(n+7), d(n+7);
for (int i = 1; i <= n; i ++) {
for (auto j : g[i]) {
sm[i][j.c] += j.d;
d[i][j.c] = INF;
if (i == 1) d[i][j.c] = 0;
}
d[i][-1] = INF;
}
d[1][-1] = 0;
set<ed> s;
for (int i = 1; i <= n; i ++) {
for (auto j : g[i]) {
s.insert({d[i][j.c], i, j.c});
}
s.insert({d[i][-1], i, -1});
}
while (!s.empty()) {
ed p = *s.begin();
s.erase(s.begin());
//cout << p.v << ' ' << p.c << ' ' << p.d << endl;
if (p.d != -1) {
for (auto i : gc[p.c][p.d]) {
if (d[i.fr][-1] > p.v+sm[p.c][p.d]-i.se) {
s.erase({d[i.fr][-1], i.fr, -1});
d[i.fr][-1] = p.v+sm[p.c][p.d]-i.se;
s.insert({d[i.fr][-1], i.fr, -1});
}
}
}
else {
for (auto i : g[p.c]) {
//cout << i.c << ' ' << i.d << ' ' << sm[p.c][p.d] << endl;
if (d[i.v][-1] > p.v+min(i.d, sm[p.c][i.c]-i.d) && s.find({d[i.v][-1], i.v, -1}) != s.end()) {
s.erase({d[i.v][-1], i.v, -1});
d[i.v][-1] = p.v+min(i.d, sm[p.c][i.c]-i.d);
s.insert({d[i.v][-1], i.v, -1});
}
if (d[i.v][i.c] > p.v) {
s.erase({d[i.v][i.c], i.v, i.c});
d[i.v][i.c] = p.v;
s.insert({d[i.v][i.c], i.v, i.c});
}
}
}
}
if (d[n][-1] == INF) cout << -1 << endl;
else cout << d[n][-1] << endl;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |