한 방향으로만 다니는 버스 노선에 정류장이 n개 있다.
첫 줄에 n이 주어진다.
둘째 줄에 정류장 이름 n개가 버스가 지나는 차례대로 빈칸으로 띄워 주어진다. 이름은 서로 다르다.
셋째 줄에 버스가 출발점을 떠나 각 정류장에 닿기까지 걸리는 시간(분) n개가 같은 차례대로 빈칸으로 띄워 주어진다. 첫 값은 0이고, 뒤로 갈수록 커진다.
넷째 줄에 물음의 수 q가 주어지고, 다음 q줄에 물음이 "A B" 꼴로 하나씩 주어진다.
물음마다 A 정류장에서 타서 B 정류장에서 내린다.
가는 정류장 칸 수(B의 차례에서 A의 차례를 뺀 값)와 걸리는 시간(분)을 빈칸 하나로 띄워 한 줄에 출력하라.
A나 B가 노선에 없거나, B가 A보다 앞에 있으면(버스는 거꾸로 가지 않는다) -1을 출력하라.
A와 B가 노선에 있는 같은 정류장이면 "0 0"을 출력한다. A와 B가 같아도 노선에 없는 이름이면 -1이다.
입력
1 ≤ n ≤ 1,000, 이름은 영어 소문자 1~10글자, 0 = 첫 시간 < … < 마지막 시간 ≤ 100,000, 1 ≤ q ≤ 1,000, 물음의 A·B도 영어 소문자 1~10글자(노선에 없을 수 있다)
출력
q줄, 줄마다 "칸 수 시간" 또는 -1
예시 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
예시 2 · stdin
2
a b
0 100000
3
a b
b a
zoo a
stdout
1 100000
-1
-1
main.py
오류 목록00F8 ↓ · ⇧F8 ↑
입력(stdin)
실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).
$ 준비됐어요
코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.
다른 언어로는?언어별 풀이 보기 · 8개 언어 풀이
이름으로 번호를 찾고(index-of), 그 번호로 다른 목록의 값을 읽는 문제예요. 찾는 방법과 못 찾았을 때가 언어마다 달라요. JS·TS stops.indexOf(a), Java List.indexOf, C# Array.IndexOf, 크레이콘 stops.자리찾기(a)는 없으면 -1을 돌려줘요. Python list.index는 없으면 ValueError를 내니 in으로 먼저 확인해요. C++ std::find는 못 찾으면 end()를 돌려주고, C 표준 라이브러리에는 배열을 차례로 훑어 찾는 함수가 없어서(bsearch는 정렬된 배열용) strcmp로 도는 함수를 직접 써요. 함정은 -1을 확인하지 않고 바로 번호로 쓰는 거예요(Python이라면 직접 만든 찾기 함수나 dict.get(a, -1)로 -1을 받았을 때). Python에서는 times[-1]이 오류 없이 맨 끝 정류장 시간이라 그럴듯한 틀린 답이 나오고, JS·TS의 times[-1]은 undefined라 NaN이 찍혀요. 거꾸로, 찾았는지를 > 0으로 물으면 번호 0인 첫 정류장을 없다고 해요. 찾음은 >= 0이나 != -1로 물어요. Java에서 입력에서 읽은 문자열을 ==로 비교하면 내용이 같아도 다른 객체라서 찾지 못해요. indexOf는 equals로 비교하니 괜찮아요. 거꾸로 가는 물음은 절댓값으로 답하지 말고 -1이에요.
Pythonmain.py · 17 줄
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 줄
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 줄
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 줄
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 줄
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 줄
#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 줄
#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", ×[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 줄
콘솔.줄읽기();stops = 콘솔.줄읽기().공백제거().나누기(" ");times = 콘솔.수들읽기();q = 콘솔.줄읽기().수로변환();반복 (t = 0; t < q; t++){ p = 콘솔.줄읽기().공백제거().나누기(" "); i = stops.자리찾기(p[0]); // 없으면 -1 j = stops.자리찾기(p[1]); 만약 (i == -1 || j == -1 || j < i) { 콘솔.쓰기(-1); } 아니면 { 콘솔.쓰기(j - i + " " + (times[j] - times[i])); }}