Each route defines a directed sequence of cities. Since Bessie wants to use only one route, for each route it is sufficient to check:
does city appear before city ?
If this condition is satisfied, Bessie can use that route and pay its fixed cost. Among all suitable routes, we need to find the route with the minimum cost.
Example
In the example, there are routes:
3 \to 2 \to 1;
2 \to 1 \to 4 \to 3;
4 \to 1 \to 7 \to 8 \to 2;
Since A = 1 and B = 2, Bessie can use only the third route, because city appears before city on that route. The cost of this route is .
Algorithm implementation
Define the constant .
#define INF 1000000000Read the input data.
scanf("%d %d %d", &a, &b, &n);Initialize the variable that will store the answer.
res = INF;Iterate over the routes.
for (i = 0; i < n; i++)
{Read the route cost and the number of cities on this route.
scanf("%d %d", &cost, &sz);The variable is set to if city has not yet appeared on the current route.
flag = false;Read the cities on the current route one by one.
for (j = 0; j < sz; j++)
{
scanf("%d", &city);If city is encountered, set to .
if (city == a) flag = true;If city is encountered and city has already appeared earlier on the route (flag = true), then Bessie can use this route and pay its cost .
If there are several suitable routes, choose the one with the minimum cost.
if (flag && city == b) res = min(res, cost);
}
}After processing all routes, print the answer.
if (res == INF)
printf("-1\n");
else
printf("%d\n", res);