1 #include <cstdio> 2 #include <queue> 3 #include <cstring> 4 #define Heap pair<int, int> 5 //第一个int存的是到起点的距离,第二个int存的是点的编号 6 7 using namespace std; 8 9 const int INF = 2147483647; 10 int n, m, t, cnt; 11 int next[1000001], to[1000001], val[1000001], head[10001], dis[10001]; 12 bool vis[1000001]; 13 priority_queue <Heap, vector <Heap>, greater <Heap> > q; 14 //按照第一个int从小到大排序 15 16 inline void add(int a, int b, int c){ 17 to[cnt] = b; 18 val[cnt] = c; 19 next[cnt] = head[a]; 20 head[a] = cnt++; 21 } 22 23 inline void Dijkstra(int s){//以s为起点 24 int i, u, v; 25 Heap x; 26 for(i = 1; i <= n; i++) dis[i] = INF; 27 dis[s] = 0; 28 q.push(make_pair(0, s));//入队 29 while(!q.empty()){ 30 x = q.top(); 31 q.pop(); 32 u = x.second; 33 if(vis[u]) continue;//判断是否已经是最短路径上的点 34 vis[u] = 1; 35 for(i = head[u]; i != -1; i = next[i]){//更新距离 36 v = to[i]; 37 if(dis[v] > dis[u] + val[i]){ 38 dis[v] = dis[u] + val[i]; 39 q.push(make_pair(dis[v], v)); 40 } 41 } 42 } 43 } 44 45 int main(){ 46 int i, j, a, b, c, s; 47 scanf("%d %d %d", &n, &m, &s); 48 memset(head, -1, sizeof(head)); 49 for(i = 1; i <= m; i++){ 50 scanf("%d %d %d", &a, &b, &c); 51 add(a, b, c); 52 } 53 Dijkstra(s); 54 for(i = 1; i <= n; i++) printf("%d ", dis[i]); 55 return 0; 56 }
优化以后的
优化的迪杰斯特拉,推荐一下
但在某些情况下慢
时间: 2024-10-10 04:28:56