题目:给出网络中各点之间的网络延迟(即距离),算出从某个点发出的信号所有点都收到的延迟。
思路:用迪杰斯特拉算法,求出网络中的所有点到当前点的最短路径,找出最大值就是答案。
算法不难但是照着书来打,实现起来还是挺麻烦的。
#define INFINITY 9999999
class Solution {
public:
int pos_min(vector<int>& dis, vector<int>& visited, int n) {
int min = INFINITY, pos = -1;
for (int i = 1; i <= n; ++i)
if (min > dis[i] && !visited[i]) {
min = dis[i];
pos = i;
}
return pos;
}
int networkDelayTime(vector<vector<int> >& times, int N, int K) {
vector<vector<int> > adj(N + 1, vector<int>(N + 1, INFINITY));
for (int i = 0; i < times.size(); ++i) {
adj[times[i][0]][times[i][1]] = times[i][2];
}
vector<int> visited(N + 1, 0);
vector<int> dis(N + 1, INFINITY);
dis[K] = 0;
int count = N;
while (count--) {
int cur = pos_min(dis, visited, N);
if (cur == -1) return -1;
visited[cur] = 1;
for (int next = 1; next <= N; ++next) {
if (dis[next] > dis[cur] + adj[cur][next]) {
dis[next] = dis[cur] + adj[cur][next];
}
}
}
int sum = 0;
for (int i = 1; i <= N; ++i)
if (sum < dis[i]) sum = dis[i];
return sum;
}
};