This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MX=5e5+5;
int N,M;
ll dist[MX];
vector<array<int,3>> adj[MX];
map<int,int> id[MX];
map<int,ll> sum[MX];
int rev[MX];
int main() {
cin.tie(0); ios_base::sync_with_stdio(0);
cin>>N>>M;
priority_queue<pair<ll,ll>> pq;
int z=N+1;
for(int i=1;i<=M;i++) {
int a,b,c,p;
cin>>a>>b>>c>>p;
sum[a][c]+=p;
sum[b][c]+=p;
if(!id[b].count(c)) {
rev[z]=b;
id[b][c]=z++;
}
if(!id[a].count(c)) {
rev[z]=a;
id[a][c]=z++;
}
adj[a].push_back({b,c,p});
adj[b].push_back({a,c,p});
adj[id[a][c]].push_back({b,c,p});
adj[b].push_back({id[a][c],c,p});
adj[id[b][c]].push_back({a,c,p});
adj[a].push_back({id[b][c],c,p});
adj[id[a][c]].push_back({id[b][c],c,p});
adj[id[b][c]].push_back({id[a][c],c,p});
}
for(int i=1;i<z;i++) {
dist[i]=1e18;
}
pq.push({0,1});
dist[1]=0;
while(!pq.empty()) {
auto [d,v]=pq.top(); pq.pop();
d=-d;
if(d>dist[v]) continue;
if(v>N) {
for(auto [u,c,p]:adj[v]) {
ll cost=sum[rev[v]][c]-p;
if(dist[u]>dist[v]+cost) {
dist[u]=dist[v]+cost;
pq.push({-dist[u],u});
}
}
} else {
for(auto [u,c,p]:adj[v]) {
if(dist[u]>dist[v]+p) {
dist[u]=dist[v]+p;
pq.push({-dist[u],u});
}
}
for(auto [u,c,p]:adj[v]) {
if(u>N) {
if(dist[u]>dist[v]) {
dist[u]=dist[v];
pq.push({-dist[u],u});
}
} else {
ll cost=sum[v][c]-p;
if(dist[u]>dist[v]+cost) {
dist[u]=dist[v]+cost;
pq.push({-dist[u],u});
}
}
}
}
}
cout<<(dist[N]==1e18?-1:dist[N])<<'\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |