#K49407. Simulate a Journey Through Towns

    ID: 28635 Type: Default 1000ms 256MiB

Simulate a Journey Through Towns

Simulate a Journey Through Towns

You are given a set of roads connecting various towns. Each road connects two towns and has an associated distance. You are also given a journey that describes a sequence of towns that must be visited in order.

The task is to simulate the journey by summing the distances between consecutive towns. If at any point there is no direct road between two successive towns, the journey is considered invalid and you should output Invalid journey. If the journey consists of less than two towns, the result should be 0.

The total distance is computed using the formula: \( D = \sum_{i=1}^{n-1} d(\text{town}_i, \text{town}_{i+1}) \).

inputFormat

The input is read from standard input (stdin) with the following format:

  1. An integer N representing the number of roads.
  2. N lines follow. Each line contains two strings and an integer separated by spaces. The two strings denote the names of towns connected by that road, and the integer is the distance between them. Note that every road is bidirectional.
  3. An integer J representing the number of towns in the journey.
  4. If J > 0, a line containing J space-separated strings representing the sequence of towns to be visited.

outputFormat

If the journey is valid, print the total distance traveled (an integer). If the journey is not possible because one or more consecutive towns are not directly connected, output Invalid journey.

## sample
4
A B 5
A C 4
B D 3
B C 2
3
A B D
8

</p>