hdu 3790 最小费用最短路

求最小费用最短路:即在路径长度尽量小的情况下使得花费尽量小。

其实就是在松弛多了一种情况就是:路径长度相等但费用小。

 1 #include <algorithm>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <cstdio>
 5 using namespace std;
 6 
 7 const int INF = 99999999;
 8 const int N = 1001;
 9 const int M = 200000;
10 int head[N];
11 int dist[N];
12 int cost[N];
13 bool visit[N];
14 int n, m, e;
15 
16 struct Edge
17 {
18     int v, next, w, c;
19 } edge[M];
20 
21 void addEdge( int u, int v, int w, int c )
22 {
23     edge[e].v = v;
24     edge[e].w = w;
25     edge[e].c = c;
26     edge[e].next = head[u];
27     head[u] = e++;
28 }
29 
30 void dij( int s )
31 {
32     memset( visit, false, sizeof(visit) );
33     for ( int i = 0; i <= n; i++ )
34     {
35         dist[i] = INF;
36         cost[i] = INF;
37     }
38     dist[s] = 0;
39     cost[s] = 0;
40     for ( int i = 1; i <= n; i++ )
41     {
42         int u = 0;
43         for ( int j = 1; j <= n; j++ )
44         {
45             if ( !visit[j] && dist[j] < dist[u] )
46             {
47                 u = j;
48             }
49         }
50         visit[u] = true;
51         for ( int j = head[u]; j != -1; j = edge[j].next )
52         {
53             int v = edge[j].v, w = edge[j].w, c = edge[j].c;
54             if ( visit[v] ) continue;
55             if ( dist[u] + w < dist[v] )
56             {
57                 dist[v] = dist[u] + w;
58                 cost[v] = cost[u] + c;
59             }
60             else if ( dist[u] + w == dist[v] && cost[u] + c < cost[v] )
61             {
62                 cost[v] = cost[u] + c;
63             }
64         }
65     }
66 }
67 
68 int main ()
69 {
70     while ( scanf("%d%d", &n, &m) != EOF )
71     {
72         if ( n == 0 && m == 0 ) break;
73         e = 0;
74         memset( head, -1, sizeof(head) );
75         while ( m-- )
76         {
77             int u, v, w, c;
78             scanf("%d%d%d%d", &u, &v, &w, &c);
79             addEdge( u, v, w, c );
80             addEdge( v, u, w, c );
81         }
82         int s, t;
83         scanf("%d%d", &s, &t);
84         dij(s);
85         printf("%d %d\n", dist[t], cost[t]);
86     }
87     return 0;
88 }

 

posted @ 2015-07-22 12:57  hxy_has_been_used  阅读(257)  评论(0编辑  收藏  举报