POJ 2387(dijkstra)

     起点是N,终点是1。单源最短路径,dijkstra。

代码:

 1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4 #define N 1001
5 #define MAX 0x7fffffff
6 int map[N][N];
7 int dis[N],flag[N];
8
9 int dijkstra(int from,int n);
10
11 /* 110 MS*/
12 int main()
13 {
14 int i,j,a,b,len,line,num;
15 scanf("%d%d",&line,&num);
16
17 for(i = 1 ; i <= num ; ++i)
18 {
19 map[i][i] = 0 ;
20 for(j = 1 ; j < i; ++j)
21 map[i][j] = map[j][i] = MAX;
22 }
23
24 for(i = 0 ; i < line ; ++i)
25 {
26 scanf("%d%d%d",&a,&b,&len);
27 if(len < map[a][b])//注意重边
28 map[a][b] = map[b][a] = len;
29 }
30 memset(flag,0,sizeof(flag));
31
32 printf("%d\n",dijkstra(num,num));
33
34 system("pause");
35 return 0;
36 }
37
38 int dijkstra(int from,int n)
39 {
40 int temp,u,i,j;
41 for(i = 1 ; i <= n ; ++i)
42 dis[i] = map[from][i];
43
44 flag[from] = 1;
45
46
47 for(j = 1 ; j < n ; ++j)
48 {
49 temp = MAX;
50
51 for(i = 1 ; i <= n ; ++i)
52 if( !flag[i] && dis[i] < temp)
53 {
54 temp = dis[i];
55 u = i ;
56 }
57
58 flag[u] = 1;
59
60 for(i = 1 ; i <= n ; ++i)
61 if( !flag[i] && map[u][i] != MAX)
62 {
63 temp = dis[u] + map[u][i];
64 if(temp < dis[i])
65 dis[i] = temp;
66 }
67
68 }//for(j)
69
70 return dis[1];
71
72 }

 

小小的优化:

 1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4 #define N 1001
5 #define MAX 0x7fffffff
6 int map[N][N];
7 int dis[N],flag[N];
8
9 int dijkstra(int from,int n);
10
11 /* 110 MS*/
12 int main()
13 {
14 int i,j,a,b,len,line,num;
15 scanf("%d%d",&line,&num);
16
17 for(i = 1 ; i <= num ; ++i)
18 {
19 map[i][i] = 0 ;
20 for(j = 1 ; j < i; ++j)
21 map[i][j] = map[j][i] = MAX;
22 }
23
24 for(i = 0 ; i < line ; ++i)
25 {
26 scanf("%d%d%d",&a,&b,&len);
27 if(len < map[a][b])//注意重边
28 map[a][b] = map[b][a] = len;
29 }
30 memset(flag,0,sizeof(flag));
31
32 printf("%d\n",dijkstra(num,num));
33
34 system("pause");
35 return 0;
36 }
37
38 int dijkstra(int from,int n)
39 {
40 int temp,u,i,j;
41 for(i = 1 ; i <= n ; ++i)
42 dis[i] = map[from][i];
43
44 flag[from] = 1;
45
46
47 for(j = 1 ; j < n ; ++j)
48 {
49 temp = MAX;
50
51 for(i = 1 ; i <= n ; ++i)
52 if( !flag[i] && dis[i] < temp)
53 {
54 temp = dis[i];
55 u = i ;
56 }
57
58 flag[u] = 1;
59 if(u == 1)//可能提前就求出来了
60 return dis[1];
61
62 for(i = 1 ; i <= n ; ++i)
63 if( !flag[i] && map[u][i] != MAX)
64 {
65 temp = dis[u] + map[u][i];
66 if(temp < dis[i])
67 dis[i] = temp;
68 }
69
70 }//for(j)
71
72 // return dis[1];
73 }

 

posted @ 2011-12-28 21:47  开开甲  阅读(330)  评论(0编辑  收藏  举报