solution.cpp 1.2 KB
Newer Older
CSDN问答's avatar
CSDN问答 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#include <iostream>
#include <cstring>
#include <queue>
#include <climits>

using namespace std;

const int N = 1e3 + 10, M = 2e6 + 10;

int h[N], e[M], ne[M], w[M], idx;
int dist[N];
int n, m, k;
bool st[N]; // 标记数组

// 初始化
void init() {
  memset(h, -1, sizeof h);
  idx = 0;
}

// 添加一条边
void add(int a, int b, int c) {
  e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}

// Dijkstra 算法求最短路径
void dijkstra(int s) {
  memset(dist, 0x3f, sizeof dist);
  dist[s] = 0;

  priority_queue<pair<int, int>> q; // 小根堆
  q.push({0, s});

  while (q.size()) {
    auto t = q.top();
    q.pop();
    int ver = t.second, distance = t.first;
    if (st[ver]) continue;
    st[ver] = true;

    // 更新所有 ver 相邻的点
    for (int i = h[ver]; ~i; i = ne[i]) {
      int j = e[i];
      if (dist[j] > distance + w[i]) {
        dist[j] = distance + w[i];
        q.push({dist[j], j});
      }
    }
  }
}

int main() {
  // 读入
  scanf("%d%d%d", &n, &m, &k);
  init();

  // 建图
  while (m--) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    add(a, b, c);
  }

  // 求最短路径
  dijkstra(1);

  // 输出最短路径
  printf("%d\n", dist[n]);

  return 0;
}