前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、网络延迟时间
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
/* 标记未被探索的节点距离 */
const int inf = INT_MAX/2;
/* 邻接表 */
vector<vector<int>> graph(n, vector<int>(n, inf));
/* 构图 */
for (vector<int> time : times)
graph[time[0] - 1][time[1] - 1] = time[2];
vector<int> dist(n, inf); // 所有节点未被探索时距离都初始化为无穷
vector<bool> used(n, false); // 标记是否已经被加入树中
dist[k - 1] = 0; // 记录原点距离为0
for (int i = 0; i < n; i++) {
int x = -1;
/* 找出候选集中到S距离最短的节点 */
for (int y = 0; y < n; y++)
if (!used[y] && (x == -1 || dist[y] < dist[x])) x = y;
/* 加入树中 */
used[x] = true;
/* 基于x 对所有x的邻节点进行松弛操作 */
for (int y = 0; y < n; y++)
dist[y] = min(dist[y], dist[x] + graph[x][y]);
}
/* 取出最短路中的最大值 */
int ans = *max_element(dist.begin(), dist.end());
return ans == inf ? -1 : ans;
}
};
二、 K站中转内最便宜的航班
class Solution {
int N = 110, INF = 0x3f3f3f3f;
int[][] g = new int[N][N];
int[] dist = new int[N];
int n, m, s, t, k;
public int findCheapestPrice(int _n, int[][] flights, int _src, int _dst, int _k) {
n = _n; s = _src; t = _dst; k = _k + 1;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
g[i][j] = i == j ? 0 : INF;
}
}
for (int[] f : flights) {
g[f[0]][f[1]] = f[2];
}
int ans = bf();
return ans > INF / 2 ? -1 : ans;
}
int bf() {
Arrays.fill(dist, INF);
dist[s] = 0;
for (int limit = 0; limit < k; limit++) {
int[] clone = dist.clone();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[j] = Math.min(dist[j], clone[i] + g[i][j]);
}
}
}
return dist[t];
}
}
总结
世上无难事,只有biubiubiu~