problem:https://leetcode.com/problems/network-delay-time
相当于求单源带权最短路径。然后取所有最短路径中最大的那个。
class Solution { public: vector<unordered_map<int, int>> graph; int networkDelayTime(vector<vector<int>>& times, int N, int K) { graph.resize(N + 1); for (auto& time : times) { graph[time[0]][time[1]] = time[2]; } vector<int> dist(N + 1, INT_MAX); priority_queue<pair<int,int>, vector<pair<int, int>>,greater<pair<int,int>>> pq; pq.push({ 0, K }); dist[K] = 0; vector<bool> visit(N + 1, false); while (!pq.empty()) { int cur = pq.top().second; pq.pop(); visit[cur] = true; for (auto& neighbor : graph[cur]) { int next = neighbor.first; int weight = neighbor.second; dist[next] = min(dist[next], dist[cur] + weight); if (!visit[next]) { pq.push({ weight, next }); } } } int res = *max_element(dist.begin() + 1, dist.end()); return res == INT_MAX ? -1 : res; } };