Network Delay Time - LeetCode
题目:
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.
考前刷的一道题,正好考试考到了,可惜没有打印出来。
题目会给出一幅图中各条边权值,然后给出一个起点,从起点发出一个信号,经过多长时间能够到达所有点。
这道题就是要求起点到最远点的最短距离,用dijkstra算法就能得出结果。
在代码中我使用了set< pair<int, int> >
这样的结构来记录待遍历节点。
pair.first是cost,pair.second是节点的序号。
由于set会自动排序,会按照cost从小到大来排,最大的好处是可以记录下cost与节点的对应关系
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int start) {
start -= 1;
int n = N;
int canNotReach = 99999999;
vector< vector<int> > g(n, vector<int>(n,canNotReach));
for (int i = 0; i < times.size(); i++) {
g[times[i][0]-1][times[i][1]-1] = times[i][2];
}
// int n = g.size();
vector<int> dist(n, canNotReach);
vector<int> prev(n, -1);
dist[start] = 0;
set< pair<int, int> > s;
s.insert(make_pair(0, start));
set< pair<int,int> >::iterator it;
int maxd = 0;
int count = 0;
while (!s.empty()) {
count++;
int mind = (*s.begin()).first;
maxd = max(maxd, mind);
int node = (*s.begin()).second;
s.erase(s.begin());
for (int i = 0; i < n; i++) {
if (mind+g[node][i] < dist[i]) {
dist[i] = mind+g[node][i];
prev[i] = node;
for (it = s.begin(); it != s.end(); it++) {
if ((*it).second == i) {
s.erase(it);
break;
}
}
s.insert(make_pair(dist[i], i));
}
}
}
if (count < n) return -1;
return maxd;
}
};