#include <bits/stdc++.h>
#define pii pair<int,int>
#define pb push_back
#define ll long long
#define MOD 1000000007
#define all(x) x.begin(),x.end()
#define MOD2 998244353
using namespace std;
void solve(int cas){
int n,m; cin>>n>>m;
using tll = tuple<ll,ll,ll,ll>;
vector<vector<tll>> g(n);
vector<map<ll,vector<ll>>> ct(n);
vector<map<ll,ll>> sm(n);
for (int i = 0; i < m; i++){
int a,b,c,d; cin>>a>>b>>c>>d;
--a;--b;
g[a].emplace_back(make_tuple(b,c,d,0));
g[b].emplace_back(make_tuple(a,c,d,0));
ct[a][c].emplace_back(b);
ct[b][c].emplace_back(a);
sm[a][c]+=d;
sm[b][c]+=d;
}
priority_queue<pair<ll,ll>, vector<pair<ll,ll>>, greater<pair<ll,ll>>> heap;
heap.push(make_pair(0,0));
for (int i = 0; i < n; i++){
vector<tll> pt;
for (auto& [neighbor, col, cc, we]: g[i]){
if (ct[neighbor][col].size()==2){
pt.emplace_back(make_tuple(ct[neighbor][col][0]==i ? ct[neighbor][col][1]: ct[neighbor][col][0], col, LLONG_MAX, cc));
}
}
for (auto& x: pt) g[i].emplace_back(x);
}
vector<ll> dp(n, LLONG_MAX);
dp[0] = 0;
while (!heap.empty()){
auto [weight, node] = heap.top(); heap.pop();
if (dp[node] < weight) continue;
if (node==n-1){
cout << weight << '\n';
return;
}
for (auto& [neighbor, col, cc, we]: g[node]){
if (we){
if (weight + we < dp[neighbor]){
dp[neighbor] = weight + we;
heap.push(make_pair(dp[neighbor], neighbor));
}
continue;
}
if (weight + min(cc, sm[node][col]-cc)*(ct[node][col].size() > 1) < dp[neighbor]){
dp[neighbor] = weight + min(cc, sm[node][col]-cc)*(ct[node][col].size() > 1);
heap.push(make_pair(dp[neighbor],neighbor));
}
}
}
cout << -1 << '\n';
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t = 1;
//cin>>t;
for (int i = 1; i <= t; i++){
solve(i);
}
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... |