Shortest Path Problem
Time limit:2000/1000 MS (java/others) Memory limit:32768/32768 K (java/others) total submission (s): 14316 Accepted Submission (s): 4385
Problem Description
Give you n points, M without the edge, each side has a length D and spend P, give you the beginning of the end of T, the minimum distance from the output starting point to the end point and the cost, if the shortest distance there are multiple routes, the output is the least cost.
Input
Enter N,m, the number of the point is 1~n, then the M line, 4 number per line a,b,d,p, indicating A and B have an edge, and its length is D, the cost is P. The last line is two number s,t; start s, end point. N and m are 0 o'clock input end.
(1<n<=1000, 0<m<100000, s! = t)
Output
The output line has two numbers, the shortest distance and the cost.
Sample Input
3 2
1 2 5 6
2 3 4 5
1 3
0 0
Sample Output
9 11
Source
Computer Postgraduate examination of University of Zhejiang University-2010
The main topic: The above is very clear, the side of the cost of more. Find the shortest path between two points in the graph,
If the shortest path has more than one, the output spends the least.
Idea: Dijkstra algorithm to find single source shortest path, when updating the path if the distance is equal, then more
New cost. Finally, note the input when the judgment, avoid the heavy edge.
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring>using namespace std;const int maxn = 1010;int Map[maxn][maxn],cost[maxn][maxn],dist[maxn],value[maxn],n,m;bool vis[MAXN];void Dijkstra (int n,int s) {int Min; for (int i = 1; I <= N; ++i) {if (i! = s) {Dist[i] = Map[s][i]; Value[i] = Cost[s][i]; }} Dist[s] = 0; Vis[s] = true; for (int i = 1; I <= N-1; ++i) {Min = 0xffffff0; int k = 0; for (int j = 1; j <= N; ++j) {if (!vis[j] && dist[j] < min) {min = Dist[j]; K = J; }} if (k = = 0) return; Vis[k] = true; for (int j = 1; j <= N; ++j) {if (!vis[j] && map[k][j]! = 0xfffff0 && Dist[j] > Dis T[K] + map[k][j]) {dist[j] = Dist[k] + map[k][j]; VALUE[J] = value[K] + cost[k][j]; } else if (!vis[j] && map[k][j]! = 0xfffff0 && Dist[j] = = Dist[k] + map[k][j]) { if (Value[j] > Value[k] + cost[k][j]) value[j] = Value[k] + cost[k][j]; }}}}int Main () {int a,b,d,p; while (~SCANF ("%d%d", &n,&m) && (n| | M) {for (int i = 1, i <= N; ++i) for (int j = 1; j <= N; ++j) map[i][j] = Cost[i ][J] = 0xffffff0; memset (vis,false,sizeof (VIS)); memset (dist,0,sizeof (Dist)); memset (value,0,sizeof (Value)); for (int i = 0; i < M; ++i) {scanf ("%d%d%d%d", &a,&b,&d,&p); if (Map[a][b] > D) {map[a][b] = map[b][a] = D; COST[A][B] = cost[b][a] = p; } else if (map[a][b] = = d) {Map[a][b] = map[b][a] = D; if (Cost[a][b] > P) COST[A][B] = p; }} scanf ("%d%d", &a,&b); Dijkstra (N,a); printf ("%d%d\n", dist[b],value[b]); } return 0;}
HDU3790 Shortest path problem "Dijsktra algorithm"