跳到正文

个人记录

dij

SleepinGod约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年10月3日
收录
2026年10月3日
更新
2026年11月3日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>

using namespace std;

const long long N = 1e5 + 5;

long long n, m, sx, f[N];

struct S {
  long long x, w;
};

vector<S> v[N];

struct A {
  long long x, val;
  friend bool operator < (const A &X, const A &Y) {
    return X.val > Y.val; // 表示取距离小的(这个如果你不懂的话我可以电话讲)
  }
}; 

priority_queue<A> pq;

bool vis[N];

void Dij() {
  memset(f, 0x3f, sizeof(f)); // 最开始是最大值
  f[sx] = 0;
  for (pq.push({sx, 0}); !pq.empty();) {
    A cur = pq.top(); // 每次取出当前未松弛的点中距离最短的
    pq.pop();
    if (vis[cur.x]) {
      continue;
    }  // 如果被松驰过就跳过
    vis[cur.x] = 1; // 标记为被松弛过
    for (long long i = 0; i < v[cur.x].size(); i++) {
      long long nx = v[cur.x][i].x;
      long long o = v[cur.x][i].w + cur.val;
      if (f[nx] > o) { // 如果可以更新就更新
        f[nx] = o;
        pq.push({nx, o});
      }
    }
  }  
}

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  cin >> n >> m >> sx;
  for (long long x, y, w; m--;) {
    cin >> x >> y >> w;
    v[x].push_back({y, w});
  }
  Dij();
  for (long long i = 1; i <= n; i++) {
    cout << f[i] << " ";
  }
  return 0;
}
原文