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 37 38 39 40 41 42 43 44 45
| class Solution { public:
typedef pair<int, int> PII; typedef pair<long long, int> PLLI;
long long minimumWeight(int n, vector<vector<int>>& edges, int src1, int src2, int dest) { vector<PII> grid[n], fgrid[n]; for (auto &e: edges) { grid[e[0]].emplace_back(e[1], e[2]); fgrid[e[1]].emplace_back(e[0], e[2]); } vector<long long> dist1(n, 1e15), dist2(n, 1e15), dist3(n, 1e15);
dijkstra(src1, grid, dist1); dijkstra(src2, grid, dist2); dijkstra(dest, fgrid, dist3); long long res = 1e15;
for (int i = 0; i < n; i ++) { res = min(res, dist1[i] + dist2[i] + dist3[i]); } if (res > 1e12) { return -1; } return res; }
void dijkstra(int s, vector<PII> grid[], vector<long long> &dist) { priority_queue<PLLI, vector<PLLI>, greater<PLLI>> q; dist[s] = 0; q.emplace(0, s); while (q.size()) { auto [cost, node] = q.top(); q.pop(); if (cost > dist[node]) continue; for (auto [ne, w]: grid[node]) { if (cost + w < dist[ne]) { dist[ne] = cost + w; q.emplace(cost + w, ne); } } } } };
|