## 原题

There are `N` network nodes, labelled `1` to `N`.

Given `times`, a list of travel times as directed edges `times[i] = (u, v, w)`, where `u` is the source node, `v` is the target node, and `w` is the time it takes for a signal to travel from source to target.

Now, we send a signal from a certain node `K`. How long will it take for all nodes to receive the signal? If it is impossible, return `-1`.

Note:

1. `N` will be in the range `[1, 100]`.
2. `K` will be in the range `[1, N]`.
3. The length of `times` will be in the range `[1, 6000]`.
4. All edges `times[i] = (u, v, w)` will have `1 <= u, v <= N` and `1 <= w <= 100`.

## 代码

[code lang=”cpp”]
typedef pair<int, int> pii;

class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
vector<vector<pii>> nodes(N + 1, vector<pii>{});
for (auto time : times) {
nodes[time[0]].push_back(make_pair(time[1], time[2]));
}
// declare vars
priority_queue<pii, vector<pii>, greater<pii> > pq; // pii 0 for city index, 1 for cost time
pq.push(make_pair(K, 0));
vector<int> time(N + 1, INT_MAX);
time[K] = 0;
while (!pq.empty()) {
pii node = pq.top();
pq.pop();
// update the time for the sub-nodes
for (auto snode : nodes[node.first]) {
if (time[snode.first] > time[node.first] + snode.second) {
time[snode.first] = time[node.first] + snode.second;
// add the valid sub-node to priority_queue
pq.push(make_pair(snode.first, time[snode.first]));
}
}
}
int a = -1;
for (int i = 1; i < time.size(); ++i) {
if (a < time[i]) a = time[i];
}
return a == INT_MAX ? -1 : a;
}
};
[/code]

E代表times的长度

Share:

## 1 Comment

1. 匿名网友 says:

人生如白驹过隙，每天浏览几篇博客，学习学习，充实自己！

This site uses Akismet to reduce spam. Learn how your comment data is processed.