Taxi#9608

Taxi (Editorial)

In a weighted graph, Dijkstra's algorithm is used to determine:

Without picking up Sergey, Ivan travels a distance of dist_{ac}.

With a detour to pick up Sergey, the total distance becomes dist_{ab} + dist_{bc}.

The answer to the problem is:

(dist_{ab} + dist_{bc} - dist_{ac}) * d

This is the additional amount the trip costs due to picking up Sergey.

Example

The road graph is as follows:

Let’s compute the shortest distances:

The distance Ivan travels without picking up Sergey: dist_{ac} = 7.5.

The distance with a detour to pick up Sergey: dist_{ab} + dist_{bc} = 5.5 + 8 = 13.5.

Thus, the answer to the problem is:

(dist_{ab} + dist_{bc} - dist_{ac}) * d = (5.5 + 8 - 7.5) * 4.25 = 6 * 4.25 = 25.5

Algorithm implementation

The graph is stored as a weighted adjacency matrix . Declare an array of shortest distances and an array , which holds information about the vertices for which the shortest distance is calculated.

#define MAX 110
double g[MAX][MAX], dist[MAX];
int used[MAX];

The Dijkstra function returns the length of the shortest path from vertex to vertex .

double Dijkstra(int s, int f)
{
  memset(used, 0, sizeof(used));
  for (i = 1; i <= n; i++) dist[i] = 1e18;
  dist[s] = 0;

  for (i = 1; i < n; i++)
  {
    double min = 1e18;
    int w = -1;
    for (j = 1; j <= n; j++)
      if (used[j] == 0 && dist[j] < min) { min = dist[j]; w = j; }

    if (min == 1e18) break;

    for (j = 1; j <= n; j++)
      if (used[j] == 0) dist[j] = minimum(dist[j], dist[w] + g[w][j]);

    used[w] = 1;
  }
  return dist[f];
}

The main part of the program. Read the input data.

scanf("%d %d %d %d %lf", &n, &a, &b, &c, &d);
scanf("%d", &m);
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++) g[i][j] = 1e18;

for (i = 0; i < m; i++)
{
  scanf("%d %d %lf", &s, &f, &w);
  g[s][f] = g[f][s] = w;
}

Compute the values of dist_{ab}, dist_{bc}, dist_{ac}.

double d1 = Dijkstra(a, b);
double d2 = Dijkstra(b, c);
double ds = Dijkstra(a, c);

If at least one of these values is equal to infinity, it means that the corresponding route does not exist — in this case print .

if (d1 == 1e18 || d2 == 1e18 || ds == 1e18) printf("-1\n");

Otherwise, print the result: (dist_{ab} + dist_{bc} - dist_{ac}) * d.

else printf("%lf\n", (d1 + d2 - ds) * d);