一道很好的题目,我使用了三种不同的写法,大家一定要每种都熟练掌握。
先来搞定下两种存储方式:
int h[N], e[M], w[M], ne[M], idx;
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int w[a][b]; // 点a到点b的权是w[a][b]
必须掌握的基础算法, 基于贪心得来。
堆优化版本大家自己搜。不写了。
const int N = 110, M = 6010, INF = 0x3f3f3f3f;
int w[N][N];
int dist[N];
int n, k;
bool st[N];
class Solution {
public:
void dijkstra()
{
memset(dist, INF, sizeof dist); //注意初始化dist到一个大数,我们才可以用较小值更新
memset(st, false, sizeof st);
dist[k] = 0;
for (int p = 1; p <= n; p++) {
// 每次找到「最短距离最小」且「未被更新」的点 t
int t = -1;
for (int i = 1; i <= n; i++) {
if (!st[i] && (t == -1 || dist[i] < dist[t])) t = i;
}
// 标记点 t 为已更新
st[t] = true;
// 用点 t 的「最小距离」更新其他点
for (int i = 1; i <= n; i++) {
dist[i] = min(dist[i], dist[t] + w[t][i]);
}
}
}
int networkDelayTime(vector<vector<int>>& times, int _n, int _k) {
n = _n, k = _k;
for (int i = 1; i <= n; i ++)
{
for (int j = 1; j <= n; j ++)
{
if (i == j) w[i][j] = 0;
else w[i][j] = INF;
}
}
for (auto e:times)
{
int a = e[0], b = e[1], c = e[2];
w[a][b] = c;
}
dijkstra();
int res = 0;
for (int i = 1; i <= n; i ++)
{
res = max(res , dist[i]);
}
if (res == INF) return -1;
return res;
}
};
大家邻接表和邻接矩阵的存储方式都需要掌握,本做法用邻接表。
const int N = 110, M = 6010, INF = 0x3f3f3f3f;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
bool st[N];
class Solution {
public:
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
void spfa(int start) { //无需初始化st是因为spfa结束条件就是所有节点出队列
queue<int> q;
q.push(start);
memset(dist, 0x3f, sizeof dist);
dist[start] = 0;
while (q.size()) {
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[t] + w[i]) {
dist[j] = dist[t] + w[i];
if (!st[j]) {
q.push(j);
st[j] = true;
}
}
}
}
}
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
memset(h, -1, sizeof h);
idx = 0;
for (auto& e: times) {
int a = e[0], b = e[1], c = e[2];
add(a, b, c);
}
spfa(k);
int res = 1;
for (int i = 1; i <= n; i ++ ) res = max(res, dist[i]);
if (res == INF) res = -1;
return res;
}
};
复杂度比较高,但是本题数据小,我最爱的无脑算法
const int N = 110, M = 6010, INF = 0x3f3f3f3f;
int w[N][N];
int n, k;
class Solution {
public:
void floyd()
{
for (int k = 1; k <= n; k ++) //k是中转站,其实flyod本质是一种dp的思想,也就是我们得到的最短路一定是靠一个最短中转站得来
{
for (int i = 1; i <= n; i ++)
{
for (int j = 1; j <= n; j ++)
{
w[i][j] = min(w[i][j], w[i][k] + w[k][j]);
}
}
}
}
int networkDelayTime(vector<vector<int>>& times, int _n, int _k) {
n = _n, k = _k;
for (int i = 1; i <= n; i ++)
{
for (int j = 1; j <= n; j ++)
{
if (i == j) w[i][j] = 0;
else w[i][j] = INF;
}
}
for (auto e:times)
{
int a = e[0], b = e[1], c = e[2];
w[a][b] = c;
}
floyd();
int res = 0;
for (int i = 1; i <= n; i ++)
{
res = max(res , w[k][i]);
}
if (res == INF) return -1;
else return res;
}
};
因篇幅问题不能全部显示,请点此查看更多更全内容