[LeetCode] Minimum Weighted Subgraph With the Required Paths

2203. Minimum Weighted Subgraph With the Required Paths

You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1.

You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti.

Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph.

Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1.

A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges.

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
class Solution {
vector<unsigned long long> build(int n, vector<vector<pair<int,int>>>& edges, int from) {
vector<unsigned long long> g(n, LLONG_MAX);
g[from] = 0;
priority_queue<pair<unsigned long long, int>, vector<pair<unsigned long long, int>>, greater<pair<unsigned long long, int>>> pq;
pq.push({0, from});
while(!pq.empty()) {
auto [cost, node] = pq.top(); pq.pop();
if(g[node] != cost) continue;
for(auto [near, weight]: edges[node]) {
if(cost + weight < g[near]) {
g[near] = cost + weight;
pq.push({g[near], near});
}
}
}
return g;
}
bool reachAble(vector<unsigned long long>& g, int to) {
return g[to] != LLONG_MAX;
}
public:
long long minimumWeight(int n, vector<vector<int>>& edges, int src1, int src2, int dest) {
vector<vector<pair<int,int>>> e(n);
vector<vector<pair<int,int>>> re(n);
for(auto edge : edges) {
e[edge[0]].push_back({edge[1], edge[2]});
re[edge[1]].push_back({edge[0], edge[2]});
}
vector<unsigned long long> src1G = build(n, e, src1);
vector<unsigned long long> src2G = build(n, e, src2);
vector<unsigned long long> destG = build(n, re, dest);

unsigned long long res = LLONG_MAX;
for(int i = 0; i < n; i++) {
if(reachAble(src1G, i) and reachAble(src2G, i) and reachAble(destG, i)) {
res = min(res, src1G[i] + src2G[i] + destG[i]);
}
}
return res == LLONG_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/13/PS/LeetCode/minimum-weighted-subgraph-with-the-required-paths/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.