第一行为源点个数,边的个数m
接下来m行为a->b和权值
6 9
1 2 1
1 3 12
2 3 9
2 4 3
3 5 5
4 3 4
4 5 13
4 6 15
5 6 4
求最短路径
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 using namespace std; 5 #define inf 1000000000 6 int e[100][100], dis[100]; 7 int main() 8 { 9 int book[100] = { 0 }; 10 int n, m; 11 scanf("%d %d", &n, &m); 12 for (int i = 1; i <= n; i++) 13 for (int j = 1; j <= n; j++) 14 { 15 if (i == j) e[i][j] = 0; 16 else e[i][j] = inf; 17 } 18 for (int i = 0; i < m; i++) 19 { 20 int a, b, c; 21 cin >> a >> b >> c; 22 e[a][b] = c; 23 } 24 for (int i = 1; i <= n; i++) 25 dis[i] = e[1][i]; 26 book[1] = 1; 27 for (int i = 1; i < n; i++) 28 { 29 int temp = inf,mark = 0; 30 for (int j = 1; j <= n; j++) 31 { 32 if (book[j] == 0 && dis[j] < temp) 33 { 34 temp = dis[j]; 35 mark = j; 36 } 37 } 38 book[mark] = 1; 39 for (int i = 1; i <= n; i++) 40 { 41 if (e[mark][i] < inf) 42 { 43 dis[i] = min(e[mark][i] + dis[mark], dis[i]); 44 } 45 } 46 } 47 for (int i = 1; i <= n; i++) 48 cout << dis[i] << endl; 49 50 return 0; 51 }