wenbao与最短路(dfs)

 

 http://hihocoder.com/problemset/problem/1081

 

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <vector>
 4 using namespace std;
 5 const int maxn = 1e3+10;
 6 int n, m, a, b, c, map[maxn][maxn], num[maxn];
 7 vector<int> T[maxn];
 8 void dfs(int x, int sum){
 9     if(num[x] == 0 || num[x] > sum) num[x] = sum;
10     else return ;
11     for(int i =0; i < T[x].size(); i++){
12         dfs(T[x][i], sum + map[x][T[x][i]]);
13     }
14 }
15 int main(){
16     scanf("%d %d", &n, &m);
17     for(int i = 0; i < n; i++){
18         scanf("%d %d %d", &a, &b, &c);
19         if(!map[a][b]){
20             T[a].push_back(b);
21             T[b].push_back(a);
22             map[a][b] = map[b][a] = c;
23         }
24         else map[a][b] = map[b][a] = min(map[a][b] , c);
25     }
26     dfs(1, 0);
27     printf("%d\n", num[m]);
28     return 0;
29 }

 

 

 

 

http://hihocoder.com/problemset/problem/1089

 

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <vector>
 4 using namespace std;
 5 const int maxn = 1e3+10;
 6 int n, m, a, b, c, map[maxn][maxn], map2[maxn][maxn];
 7 vector<int> T[maxn];
 8 void dfs(int start, int x, int sum){
 9     if(map2[start][x] == 0 || map2[start][x] > sum) map2[start][x] = sum;
10     else return ;
11     for(int i =0; i < T[x].size(); i++){
12         dfs(start, T[x][i], sum + map[x][T[x][i]]);
13     }
14 }
15 int main(){
16     scanf("%d %d", &n, &m);
17     for(int i = 0; i < m; i++){
18         scanf("%d %d %d", &a, &b, &c);
19         if(!map[a][b]){
20             T[a].push_back(b);
21             T[b].push_back(a);
22             map[a][b] = map[b][a] = c;
23         }
24         else map[a][b] = map[b][a] = min(map[a][b] , c);
25     }
26     for(int i = 1; i <= n; i++)
27         dfs(i, i, 0), map2[i][i] = 0;
28     for(int i = 1; i <= n; i++){
29         for(int j = 1; j <= n; j++){
30             if(j!=n)
31                 printf("%d ", map2[i][j]);
32             else
33                 printf("%d\n", map2[i][j]);
34         }
35     }
36     return 0;
37 }

 

 

 

只有不断学习才能进步!

 

posted @ 2018-04-14 13:55  wenbao  阅读(168)  评论(0编辑  收藏  举报