[백준 5145] Subway Fares (C#, C++) - soo:bak
작성일 :
문제 링크
설명
한 지하철 노선의 요금표와 역 순서가 주어질 때, 출발역과 도착역 사이의 이동 요금을 구하는 문제입니다.
접근법
요금은 이동한 정거장 수로만 결정되므로, 먼저 요금표를 배열에 저장합니다.
그 다음 역 이름을 순서대로 읽으면서 각 역의 위치를 기록해 둡니다. 출발역과 도착역의 위치 차이의 절댓값이 이동한 정거장 수이고, 그 값을 인덱스로 해서 요금표에서 바로 꺼내면 됩니다.
출력은 데이터셋 번호와 정답 사이에 빈 줄까지 포함해 문제 형식에 맞춰 그대로 출력합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Collections.Generic;
class Program {
static void Main() {
int t = int.Parse(Console.ReadLine()!);
for (int tc = 1; tc <= t; tc++) {
int n = int.Parse(Console.ReadLine()!);
int[] fare = new int[n];
for (int s = 1; s <= n - 1; s++) {
fare[s] = int.Parse(Console.ReadLine()!);
}
var index = new Dictionary<string, int>();
for (int i = 0; i < n; i++) {
string station = Console.ReadLine()!;
index[station] = i;
}
string start = Console.ReadLine()!;
string end = Console.ReadLine()!;
int distance = Math.Abs(index[start] - index[end]);
Console.WriteLine($"Data Set {tc}:");
Console.WriteLine(fare[distance]);
Console.WriteLine();
}
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
for (int tc = 1; tc <= t; tc++) {
int n;
cin >> n;
vector<int> fare(n, 0);
for (int s = 1; s <= n - 1; s++) {
cin >> fare[s];
}
unordered_map<string, int> index;
for (int i = 0; i < n; i++) {
string station;
cin >> station;
index[station] = i;
}
string start, end;
cin >> start >> end;
int distance = abs(index[start] - index[end]);
cout << "Data Set " << tc << ":\n";
cout << fare[distance] << "\n\n";
}
return 0;
}