-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3650.Minimum-Cost-Path-with-Edge-Reversals.cpp
More file actions
36 lines (36 loc) · 1.18 KB
/
3650.Minimum-Cost-Path-with-Edge-Reversals.cpp
File metadata and controls
36 lines (36 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
int minCost(int n, vector<vector<int>>& edges) {
using State=tuple<long long, int, int>;
vector<vector<pair<int,int>>>out(n), in(n);
for(auto &e:edges){
out[e[0]].push_back({e[1], e[2]});
in[e[1]].push_back({e[0], e[2]});
}
vector<vector<long long>>dist(n, vector<long long>(2, LLONG_MAX));
priority_queue<State, vector<State>, greater<State>>pq;
dist[0][0]=0;
pq.push({0,0,0});
while(!pq.empty()){
auto [cost, u, used]=pq.top();
pq.pop();
if(cost>dist[u][used]) continue;
for(auto [v,w]:out[u]){
if(dist[v][0]>cost+w){
dist[v][0]=cost+w;
pq.push({dist[v][0], v, used});
}
}
if(used==0){
for(auto [v,w]:in[u]){
if(dist[v][0]>cost+2LL*w){
dist[v][0]=cost+2LL*w;
pq.push({dist[v][0], v, 0});
}
}
}
}
long long ans=min(dist[n-1][0], dist[n-1][1]);
return ans==LLONG_MAX?-1:ans;
}
};