例题:https://www.luogu.org/problemnew/show/3371
1 #include <cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<queue> 5 #include<vector> 6 #include<cstring> 7 #include<algorithm> 8 using namespace std; 9 vector<int>v[10005], c[10005]; 10 const int INF = 2147483647; 11 int dis[10005]; 12 bool vis[10005]; 13 void sssp(int a) //single source shortest path 14 { 15 for(int i = 0; i < 10005; ++i) dis[i] = INF; 16 dis[a] = 0; 17 memset(vis, 0, sizeof(vis)); 18 queue<int>q;q.push(a); 19 while(!q.empty()) 20 { 21 int now = q.front();q.pop(); 22 vis[now] = 0; 23 for(int i = 0; i < (int)v[now].size(); ++i) 24 { 25 if(dis[now] + c[now][i] < dis[v[now][i]]) 26 { 27 dis[v[now][i]] = dis[now] + c[now][i]; 28 if(vis[v[now][i]] == 0) 29 q.push(v[now][i]); vis[v[now][i]] = 1; 30 } 31 } 32 } 33 } 34 int main() 35 { 36 int n, m, s; 37 scanf("%d%d%d", &n, &m, &s); 38 for(int i = 0; i < m; ++i) 39 { 40 int f, g, w; 41 scanf("%d%d%d", &f, &g, &w); 42 v[f].push_back(g);c[f].push_back(w); 43 } 44 sssp(s); 45 for (int i = 1; i <= n; i++){ 46 printf("%d%c", dis[i], i == n ? ‘\n‘ : ‘ ‘); 47 } 48 }