dijkstra
洛谷模板题链接:https://www.luogu.org/problem/P3371
1 #include <iostream> 2 #include <vector> 3 #include <cstring> 4 #include <cstdio> 5 using namespace std; 6 const int N = 1e5 + 10; 7 const int INF = 2147483647; 8 9 //n = 顶点数; m = 边数; s = 起点 10 int n, m, s; 11 12 //第一个数是距离,第二个数为顶点 13 vector<pair<int,int> > g[N]; 14 int dist[N]; 15 bool vis[N]; 16 17 void dijkstra(int s) 18 { 19 memset(vis, 0, sizeof(vis)); 20 for(int i = 1; i <= n; i++) dist[i] = INF; 21 dist[s] = 0; 22 while(1) 23 { 24 int node = -1; 25 int minDist = INF; 26 27 //在为标记的点中找到距离起点的最短距离 28 for(int i = 1; i <= n; i++) 29 { 30 if(vis[i] == 0 && dist[i] < minDist) 31 { 32 node = i; 33 minDist = dist[i]; 34 } 35 } 36 37 if(node == -1) break; 38 //标记该点 39 vis[node] = 1; 40 41 //更新 42 for(int i = 0; i < g[node].size(); i++) 43 { 44 int v = g[node][i].second; 45 dist[v] = min(dist[v], dist[node] + g[node][i].first); 46 } 47 48 } 49 } 50 51 int main() 52 { 53 cin >> n >> m >> s; 54 for(int i = 1; i <= m; i++) 55 { 56 int u, v, d; 57 scanf("%d %d %d", &u, &v, &d); 58 g[u].push_back(make_pair(d, v)); 59 } 60 dijkstra(s); 61 for(int i = 1; i <= n; i++) 62 i==1?cout<<dist[i]:cout<<" "<<dist[i]; 63 return 0; 64 }
这是没有加优化的,数据加强的话,就会TLE。