Created
May 21, 2023 04:18
-
-
Save tdzl2003/d214e559f1979fa55fb11672d6dfbbbc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<int>> modifiedGraphEdges(int n, vector<vector<int>>& edges, int source, int destination, int target) { | |
vector<vector<pair<int, int>>> graph(n); | |
for (int i = 0; i < edges.size(); i++) { | |
graph[edges[i][0]].push_back({ edges[i][1], i }); | |
graph[edges[i][1]].push_back({ edges[i][0], i }); | |
} | |
vector<int> route; | |
long long max = dijkstra(graph, edges, source, destination, 2000000000, route); | |
if (max < target) { | |
return {}; | |
} | |
bool first = true; | |
for (;;) { | |
long long min = dijkstra(graph, edges, source, destination, 1, route); | |
if (min > target) { | |
return {}; | |
} | |
if (min == target) { | |
for (auto v : route) { | |
if (edges[v][2] == -1) { | |
edges[v][2] = 1; | |
} | |
} | |
return edges; | |
} | |
int last = -1; | |
for (auto v : route) { | |
if (edges[v][2] == -1) { | |
last = v; | |
break; | |
} | |
} | |
if (first) { | |
first = false; | |
set<int> s(route.begin(), route.end()); | |
for (int i = 0; i < edges.size() ;i++){ | |
auto& v = edges[i]; | |
if (v[2] == -1 && s.find(i) == s.end()) { | |
v[2] = 2000000000; | |
} | |
} | |
} | |
edges[last][2] = target - min + 1; | |
} | |
} | |
long long dijkstra(vector<vector<pair<int, int>>>& graph, vector<vector<int>>& edges, int source, int destination, int def, vector<int>& route) { | |
int n = graph.size(); | |
vector<long long> depth(n, -1); | |
vector<int> prev(n); | |
vector<int> edge(n, -1), visited(n); | |
priority_queue<pair<long long, int>> pq; | |
depth[source] = 0; | |
prev[source] = -1; | |
pq.push({ 0, source }); | |
while (pq.size() > 0) { | |
auto el = pq.top(); | |
pq.pop(); | |
if (visited[el.second]) { | |
continue; | |
} | |
if (el.second == destination) { | |
route.clear(); | |
int v = destination; | |
while (v != source) { | |
route.push_back(edge[v]); | |
v = prev[v]; | |
} | |
return depth[el.second]; | |
} | |
visited[el.second] = 1; | |
auto cur = depth[el.second]; | |
for (auto e : graph[el.second]) { | |
auto ch = e.first; | |
auto id = e.second; | |
auto v = edges[id][2]; | |
if (v == -1) { | |
v = def; | |
} | |
if (depth[ch] >= 0 && depth[ch] <= cur + v) { | |
continue; | |
} | |
depth[ch] = cur + v; | |
prev[ch] = el.second; | |
edge[ch] = id; | |
pq.push({ -depth[ch], ch }); | |
} | |
} | |
return 2000000000; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment