首页 > 其他 > 详细

wenbao与最短路(dfs)

时间:2018-04-14 14:43:31      阅读:193      评论:0      收藏:0      [点我收藏+]

 

 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 }

 

 

 

只有不断学习才能进步!

 

wenbao与最短路(dfs)

原文:https://www.cnblogs.com/wenbao/p/5895911.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!