#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define int long long
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define FORD(i, a, b) for (int i = (b); i >= (a); i --)
#define REP(i, a) for (int i = 0; i < (a); ++i)
#define REPD(i, a) for (int i = (a) - 1; i >= 0; --i)
#define MASK(i) (1LL << (i))
#define BIT(x, i) (((x) >> (i)) & 1)
constexpr ll LINF = (1ll << 60);
constexpr int INF = (1ll << 30);
constexpr int Mod = 1e9 + 7;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
/*
Phu Trong from Nguyen Tat Thanh High School for gifted student
*/
template <class X, class Y>
bool minimize(X &x, const Y &y){
X eps = 1e-9;
if (x > y + eps) {x = y; return 1;}
return 0;
}
template <class X, class Y>
bool maximize(X &x, const Y &y){
X eps = 1e-9;
if (x + eps < y) {x = y; return 1;}
return 0;
}
#define MAX_NODE 100005
#define MAX_EDGE 200005
int numNode, numEdge;
map<int, vector<pair<int, int>>> G[MAX_NODE];
map<int, int> same_color_sum[MAX_NODE];
int dp[MAX_NODE];
map<int, int> last_dp[MAX_NODE];
void process(void){
cin >> numNode >> numEdge;
for (int i = 1; i <= numEdge; ++i){
int u, v, color, cost; cin >> u >> v >> color >> cost;
G[u][color].emplace_back(v, cost);
G[v][color].emplace_back(u, cost);
same_color_sum[u][color] += cost;
same_color_sum[v][color] += cost;
}
memset(dp, 0x3f, sizeof dp);
#define T tuple<int, int, int>
priority_queue<T, vector<T>, greater<T>> q;
q.emplace((dp[1] = 0), 1, 0);
while(q.size()){
int du, u, last_color;
tie(du, u, last_color) = q.top(); q.pop();
if(last_color == 0){
if(du > dp[u]) continue;
for (auto&c : G[u]){
int w = same_color_sum[u][c.first];
for (pair<int, int>&x : c.second){
int v = x.first, cost = x.second;
//change this edge
if(minimize(dp[v], du + cost)){
q.emplace(dp[v], v, 0);
}
//change all neighbour
if(minimize(dp[v], du + w - cost)){
q.emplace(dp[v], v, 0);
}
if (!last_dp[v].count(c.first) || last_dp[v][c.first] > du){
last_dp[v][c.first] = du;
q.emplace(last_dp[v][c.first], v, c.first);
}
}
}
}
else{
int now = last_dp[u][last_color];
int w = same_color_sum[u][last_color];
if(du != now) continue; //not optimial way
for (pair<int, int>&x : G[u][last_color]){
int cost = x.second, v = x.first;
if(minimize(dp[v], now + w - cost)){
q.emplace(dp[v], v, 0);
}
}
}
}
cout << (dp[numNode] >= LINF ? -1 : dp[numNode]);
}
signed main(){
#define name "Whisper"
cin.tie(nullptr) -> sync_with_stdio(false);
// freopen(name".inp", "r", stdin);
// freopen(name".out", "w", stdout);
process();
return (0 ^ 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... |