Tram#4033

Tram (Editorial)

Build a directed graph whose vertices are junctions and whose edges are rails. Assign to each edge a weight — the number of switch changes needed to travel along it:

In the input, the switch initially points to the first junction in the list, so the first edge of each line gets weight , and the others get weight .

Then the cost of a route equals the sum of the weights of its edges, and the answer is the length of the shortest path from to . Note that a switch never needs to be changed twice: a shortest path does not pass through a vertex more than once.

We obtain a 0-1 graph — a graph whose edge weights are or . Shortest distances in it can be found with Dijkstra's algorithm in O(m \log n), but it is faster to use breadth-first search with a deque (0-1 BFS) in O(n + m). Vertices are taken from the front of the deque. If the edge relaxes, that is, \mathit{dist}[x] + w < \mathit{dist}[y], we update and:

The deque is always sorted in non-decreasing order of distances and contains vertices with at most two adjacent distance values, so vertices are extracted in the same order as in Dijkstra's algorithm. A vertex may enter the deque twice (first via an edge of weight , then via an edge of weight ), but when it is extracted again, there will be no more improvements.

If after the search remains equal to , there is no route from to , and the answer is .

Complexity. The number of edges equals the sum of all k_i. Each vertex is added to the deque at most twice, and each edge is examined times, so the total complexity is O(n + m).

Example

Edges of weight show the initial directions of the switches: 1 \to 2, 2 \to 3, and 3 \to 1. The tram starts at junction a = 2 and must reach junction b = 1. The route 2 \to 3 \to 1 uses only edges of weight , so no switches need to be changed, and the answer is . The direct rail 2 \to 1 would require one switch change.

Let us trace the breadth-first search with a deque. Vertices added to the deque at the current step are highlighted in orange, changed distances in green.

First, vertex is added to the back of the deque with distance via the edge 2 \to 1. Then, via the edge 3 \to 1 of weight , its distance improves to , and it is put once more at the front of the deque. The old copy of vertex stays at the back, but nothing changes when it is extracted.

Algorithm Implementation

Declare the infinity constant .

#define INF 0x3F3F3F3F

Declare the array of shortest distances and the adjacency list of the graph . For each rail, together with the junction it leads to, we store its weight: if the switch points to this rail, and otherwise.

vector<int> dist;
vector<vector<pair<int, int> > > g;

The bfs function performs a breadth-first search in the 0-1 graph from vertex . Initially, the distances to all vertices are , and the distance from to itself is . A deque is used instead of an ordinary queue.

void bfs(int start)
{
  dist = vector<int>(n + 1, INF);
  dist[start] = 0;

  deque<int> q;
  q.push_back(start);

Take vertex from the front of the deque and iterate over all edges (\mathit{to}, w) outgoing from it.

  while (!q.empty())
  {
    int v = q.front(); q.pop_front();
    for (auto edge : g[v])
    {
      int to = edge.first;
      int w = edge.second;

If the path to through is shorter than the known one (the edge relaxes), update . A vertex reached by an edge of weight is put at the back of the deque, and a vertex reached by an edge of weight is put at the front: its distance equals , and it must be processed before the others.

      if (dist[to] > dist[v] + w)
      {
        dist[to] = dist[v] + w;
        if (w == 1)
          q.push_back(to);
        else
          q.push_front(to);
      }
    }
  }
}

The main part of the program. Read the number of junctions , the starting junction , and the target junction .

scanf("%d %d %d", &n, &a, &b);
g.resize(n + 1);

Read the descriptions of the junctions. For the -th junction, first read the number of rails leaving it, and then the numbers of the junctions they lead to. The first junction in the list is the one the switch initially points to: the edge to it gets weight . The other edges get weight — to travel along them, the switch must be changed.

for (i = 1; i <= n; i++)
{
  scanf("%d", &k);
  for (j = 0; j < k; j++)
  {
    scanf("%d", &to);
    w = (j == 0) ? 0 : 1;
    g[i].push_back({ to, w });
  }
}

Run the breadth-first search from vertex .

bfs(a);

Print the answer — the shortest distance to vertex . If vertex is unreachable, print .

if (dist[b] == INF)
  printf("-1\n");
else
  printf("%d\n", dist[b]);