{ }codelper
list indexingP0224

Travel time on a one-way bus route

A one-way bus route has n stops. The first line gives n. The second line gives the n stop names in the order the bus passes them, separated by spaces.
The names are all different. The third line gives, in the same order, the n times (in minutes) the bus takes from leaving the start to reach each stop, separated by spaces.
The first value is 0, and the values increase. The fourth line gives the number of queries q, and each of the next q lines gives one query in the form "A B". For each query, you get on at stop A and get off at stop B. Print on one line the number of stops travelled (B's position in the order minus A's) and the time taken in minutes, separated by one space. If A or B is not on the route, or B comes before A (the bus never goes backwards), print -1. If A and B are the same stop on the route, print "0 0".
If A and B are the same name but not on the route, the answer is -1.

Input
1 ≤ n ≤ 1,000, names are 1 to 10 lowercase English letters, 0 = first time < … < last time ≤ 100,000, 1 ≤ q ≤ 1,000, A and B in queries are also 1 to 10 lowercase letters (they may not be on the route)
Output
q lines, each "stops minutes" or -1
Example 1 · stdin
5
city park school market river
0 4 9 15 22
5
park market
city river
market park
school school
park zoo
stdout
2 11
4 22
-1
0 0
-1
Example 2 · stdin
2
a b
0 100000
3
a b
b a
zoo a
stdout
1 100000
-1
-1
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

You look up a position by name (index-of) and use that position to read another list.
How you search, and what you get when nothing is found, differs by language.
JS/TS stops.indexOf(a), Java List.indexOf, C# Array.IndexOf and Craykon stops.IndexOf(a) return -1 when the value is missing.
Python list.index raises ValueError instead, so check with in first.
C++ std::find returns end() when it finds nothing, and the C standard library has no function that scans an array for a value (bsearch needs a sorted array), so you write a loop with strcmp yourself.
The trap is using -1 as an index without checking it (in Python, when -1 comes from your own search function or dict.get(a, -1)).
In Python times[-1] is the last stop's time with no error, so you get a plausible wrong answer, and in JS/TS times[-1] is undefined, so NaN is printed.
The opposite mistake is testing for found with > 0: then the first stop, at position 0, is reported missing.
Test with >= 0 or != -1.
In Java, comparing strings read from input with == fails even when the contents are equal, because they are different objects.
indexOf compares with equals, so it is fine.
A query that goes backwards is -1, not the absolute difference.

Pythonmain.py · 17 lines
n = int(input())stops = input().split()times = list(map(int, input().split()))q = int(input())out = []for _ in range(q):    a, b = input().split()    # list.index는 없으면 ValueError를 내니 먼저 in으로 확인한다    if a not in stops or b not in stops:        out.append("-1")        continue    i, j = stops.index(a), stops.index(b)    if j < i:                       # 버스는 거꾸로 가지 않는다        out.append("-1")    else:        out.append(f"{j - i} {times[j] - times[i]}")   # 같은 번호로 다른 목록을 읽는다print("\n".join(out))
JavaScriptmain.js · 16 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const stops = lines[1].trim().split(" ");const times = lines[2].trim().split(" ").map(Number);const q = Number(lines[3]);const out = [];for (let t = 0; t < q; t++) {  const [a, b] = lines[4 + t].trim().split(" ");  const i = stops.indexOf(a); // 없으면 -1  const j = stops.indexOf(b);  if (i === -1 || j === -1 || j < i) {    out.push("-1");  } else {    out.push(`${j - i} ${times[j] - times[i]}`);  }}console.log(out.join("\n"));
TypeScriptmain.ts · 17 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const stops: string[] = lines[1].trim().split(" ");const times: number[] = lines[2].trim().split(" ").map(Number);const q: number = Number(lines[3]);const out: string[] = [];for (let t = 0; t < q; t++) {  const [a, b] = lines[4 + t].trim().split(" ");  const i: number = stops.indexOf(a); // 없으면 -1  const j: number = stops.indexOf(b);  if (i === -1 || j === -1 || j < i) {    out.push("-1");  } else {    out.push(`${j - i} ${times[j] - times[i]}`);  }}console.log(out.join("\n"));
JavaMain.java · 25 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays;import java.util.List; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        in.readLine();        List<String> stops = Arrays.asList(in.readLine().trim().split(" "));        int[] times = Arrays.stream(in.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();        int q = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int t = 0; t < q; t++) {            String[] p = in.readLine().trim().split(" ");            int i = stops.indexOf(p[0]); // 없으면 -1(문자열 내용으로 비교한다)            int j = stops.indexOf(p[1]);            if (i == -1 || j == -1 || j < i) out.append("-1");            else out.append(j - i).append(' ').append(times[j] - times[i]);            out.append('\n');        }        System.out.print(out);    }}
C#Main.cs · 25 lines
using System;using System.Linq;using System.Text; class Program{    static void Main()    {        Console.ReadLine();        string[] stops = Console.ReadLine().Trim().Split(' ');        int[] times = Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToArray();        int q = int.Parse(Console.ReadLine());        var sb = new StringBuilder();        for (int t = 0; t < q; t++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            int i = Array.IndexOf(stops, p[0]); // 없으면 -1, 첫 정류장은 0            int j = Array.IndexOf(stops, p[1]);            if (i < 0 || j < 0 || j < i) sb.Append("-1");            else sb.Append(j - i).Append(' ').Append(times[j] - times[i]);            sb.Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 28 lines
#include <algorithm>#include <iostream>#include <string>#include <vector> int main() {    std::ios::sync_with_stdio(false);    int n, q;    std::cin >> n;    std::vector<std::string> stops(n);    std::vector<int> times(n);    for (auto& s : stops) std::cin >> s;    for (int& x : times) std::cin >> x;    std::cin >> q;    for (int t = 0; t < q; t++) {        std::string a, b;        std::cin >> a >> b;        // std::find는 못 찾으면 end()를 돌려준다(번호로 치면 n)        auto ia = std::find(stops.begin(), stops.end(), a);        auto ib = std::find(stops.begin(), stops.end(), b);        if (ia == stops.end() || ib == stops.end() || ib < ia) {            std::cout << "-1\n";            continue;        }        int i = ia - stops.begin(), j = ib - stops.begin();        std::cout << j - i << " " << times[j] - times[i] << "\n";    }}
Cmain.c · 29 lines
#include <stdio.h>#include <string.h> static char stops[1000][11];static int times[1000];static int n; /* 이름이 처음 나오는 번호, 없으면 -1 */int index_of(const char *name) {    for (int i = 0; i < n; i++)        if (strcmp(stops[i], name) == 0) return i;    return -1;} int main(void) {    int q;    char a[11], b[11];    scanf("%d", &n);    for (int i = 0; i < n; i++) scanf("%10s", stops[i]);    for (int i = 0; i < n; i++) scanf("%d", &times[i]);    scanf("%d", &q);    for (int t = 0; t < q; t++) {        scanf("%10s %10s", a, b);        int i = index_of(a), j = index_of(b);        if (i == -1 || j == -1 || j < i) puts("-1");        else printf("%d %d\n", j - i, times[j] - times[i]);    }    return 0;}
Craykonmain.cray · 18 lines
Console.ReadLine();stops = Console.ReadLine().Trim().Split(" ");times = Console.ReadNumbers();q = Console.ReadLine().ToNumber();for (t = 0; t < q; t++){    p = Console.ReadLine().Trim().Split(" ");    i = stops.IndexOf(p[0]); // 없으면 -1    j = stops.IndexOf(p[1]);    if (i == -1 || j == -1 || j < i)    {        Console.WriteLine(-1);    }    else    {        Console.WriteLine(j - i + " " + (times[j] - times[i]));    }}