{ }codelper
크기 비교그리고·또는P0169

만 나이로 받는 입장료

놀이공원이 손님의 만 나이로 입장료를 정한다. 첫 줄에 오늘 날짜가, 둘째 줄에 손님 수 n이, 다음 n줄에 손님마다 태어난 날이 주어진다. 날짜는 모두 YYYY-MM-DD 꼴(월과 일은 두 자리)이고, 태어난 날은 오늘보다 늦지 않다. 만 나이는 (오늘의 연도 - 태어난 연도)에서, 올해 생일이 아직 오지 않았으면 1을 뺀 것이다. 올해 생일이 아직 오지 않았다는 것은 오늘의 월이 태어난 월보다 앞서거나, 두 월이 같고 오늘의 일이 태어난 일보다 앞선다는 뜻이다. 이 규칙대로 하면 2월 29일에 태어난 사람은 평년에는 3월 1일에 한 살 많아진다. 입장료는 만 나이가 2살 이하이면 0원, 3~12살이면 6,000원, 13~18살이면 9,000원, 19~64살이면 15,000원, 65살 이상이면 7,000원이다. 다만 오늘의 월과 일이 태어난 날의 월과 일과 모두 같으면, 곧 오늘이 생일이면 나이와 상관없이 0원이다. 손님마다 한 줄에 만 나이와 입장료를 빈칸 하나로 띄워 입력 차례대로 출력하라. 마지막 줄에 입장료의 합을 출력하라.

입력
1900-01-01 ≤ 태어난 날 ≤ 오늘 ≤ 2100-12-31, 1 ≤ n ≤ 1,000, 모든 날짜는 달력에 있는 날이다
출력
손님마다 한 줄(만 나이, 입장료), 마지막 줄에 입장료의 합
예시 1 · stdin
2025-10-01
6
2015-09-30
2015-10-02
2007-10-01
2004-02-29
1960-12-31
2023-01-15
stdout
10 6000
9 6000
18 0
21 15000
64 15000
2 0
42000
예시 2 · stdin
2023-02-28
3
2004-02-29
1958-02-28
2010-03-01
stdout
18 9000
65 0
12 6000
15000
main.py
입력(stdin)

실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).

$ 준비됐어요

코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.

다른 언어로는?언어별 풀이 보기 · 8개 언어 풀이

"생일이 지났나"를 묻는 비교가 이 문제의 전부예요.
흔한 실수는 월과 일을 따로 묻는 tm >= bm && td >= bd예요.
5월 3일에 4월 20일생을 보면 월은 지났는데 일(3 < 20) 때문에 아직 생일 전이라고 나와요.
맞는 조건은 "월이 앞서거나, 월이 같고 일이 앞선다"이고, 일곱 언어는 tm < bm || (tm == bm && td < bd), Python은 tm < bm or (tm == bm and td < bd)예요(크레이콘도 ||·&&예요).
Python 튜플 (tm, td) < (bm, bd)과 C++ std::tie(tm, td) < std::tie(bm, bd)는 앞 칸부터 차례로 비교해서 이 조건을 한 번에 써요.
JS·TS의 배열에는 이런 비교가 없어요.
[tm, td] < [bm, bd]는 두 배열을 문자열 "10,1"과 "9,30"으로 바꿔 사전 순으로 비교하니 10월 1일이 9월 30일보다 앞선다고 나와요(TS는 이 식을 막지 않아요).
Java·C#의 튜플·배열에도 <가 없어서 칸마다 비교하거나 월 × 100 + 일 같은 수 하나로 바꿔 비교해요.
날짜 문자열 "MM-DD"끼리 비교해도 월과 일이 두 자리라 사전 순이 곧 날짜 순이에요.
Python·JS·TS·크레이콘은 <, Java는 compareTo, C#은 string.CompareOrdinal, C++ std::string은 <로 돼요.
그러나 C에서 char 배열끼리 <로 비교하면 내용이 아니라 메모리 주소를 비교하니 strcmp를 써야 해요.

Pythonmain.py · 31 줄
def parse(s):    y, m, d = map(int, s.split("-"))    return y, m, d  def price(age):    if age <= 2:        return 0    elif age <= 12:        return 6000    elif age <= 18:        return 9000    elif age <= 64:        return 15000    else:        return 7000  ty, tm, td = parse(input().strip())n = int(input())total = 0for _ in range(n):    by, bm, bd = parse(input().strip())    age = ty - by    # 튜플은 앞 칸부터 차례로 비교한다: 월이 같을 때만 일을 본다    if (tm, td) < (bm, bd):        age -= 1    fee = 0 if (tm, td) == (bm, bd) else price(age)  # 생일 당일은 무료    print(age, fee)    total += feeprint(total)
JavaScriptmain.js · 24 줄
const lines = require("fs").readFileSync(0, "utf8").split("\n");const parse = (s) => s.trim().split("-").map(Number);const price = (age) => {  if (age <= 2) return 0;  else if (age <= 12) return 6000;  else if (age <= 18) return 9000;  else if (age <= 64) return 15000;  else return 7000;};const [ty, tm, td] = parse(lines[0]);const n = Number(lines[1]);const out = [];let total = 0;for (let i = 0; i < n; i++) {  const [by, bm, bd] = parse(lines[2 + i]);  // 배열끼리 <로 비교하면 문자열 "10,1" < "9,30"으로 비교된다 → 칸마다 직접 비교한다  const beforeBirthday = tm < bm || (tm === bm && td < bd);  const age = ty - by - (beforeBirthday ? 1 : 0);  const fee = tm === bm && td === bd ? 0 : price(age); // 생일 당일은 무료  out.push(`${age} ${fee}`);  total += fee;}out.push(String(total));console.log(out.join("\n"));
TypeScriptmain.ts · 25 줄
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const parse = (s: string): number[] => s.trim().split("-").map(Number);const price = (age: number): number => {  if (age <= 2) return 0;  else if (age <= 12) return 6000;  else if (age <= 18) return 9000;  else if (age <= 64) return 15000;  else return 7000;};const [ty, tm, td] = parse(lines[0]);const n = Number(lines[1]);const out: string[] = [];let total = 0;for (let i = 0; i < n; i++) {  const [by, bm, bd] = parse(lines[2 + i]);  // 배열끼리 <로 비교하면 문자열 "10,1" < "9,30"으로 비교된다 → 칸마다 직접 비교한다  const beforeBirthday = tm < bm || (tm === bm && td < bd);  const age = ty - by - (beforeBirthday ? 1 : 0);  const fee = tm === bm && td === bd ? 0 : price(age); // 생일 당일은 무료  out.push(`${age} ${fee}`);  total += fee;}out.push(String(total));console.log(out.join("\n"));
JavaMain.java · 36 줄
import java.io.BufferedReader;import java.io.InputStreamReader; public class Main {    static int[] parse(String s) {        String[] p = s.trim().split("-");        return new int[] {Integer.parseInt(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2])};    }     static int price(int age) {        if (age <= 2) return 0;        else if (age <= 12) return 6000;        else if (age <= 18) return 9000;        else if (age <= 64) return 15000;        else return 7000;    }     public static void main(String[] args) throws Exception {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int[] t = parse(in.readLine());        int n = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        long total = 0;        for (int i = 0; i < n; i++) {            int[] b = parse(in.readLine());            // 월이 앞서거나, 월이 같고 일이 앞서면 아직 생일 전이다            boolean beforeBirthday = t[1] < b[1] || (t[1] == b[1] && t[2] < b[2]);            int age = t[0] - b[0] - (beforeBirthday ? 1 : 0);            int fee = (t[1] == b[1] && t[2] == b[2]) ? 0 : price(age); // 생일 당일은 무료            out.append(age).append(' ').append(fee).append('\n');            total += fee;        }        out.append(total).append('\n');        System.out.print(out);    }}
C#Main.cs · 35 줄
using System;using System.Linq;using System.Text; class Program{    static int Price(int age)    {        if (age <= 2) return 0;        else if (age <= 12) return 6000;        else if (age <= 18) return 9000;        else if (age <= 64) return 15000;        else return 7000;    }     static void Main()    {        int[] t = Console.ReadLine().Trim().Split('-').Select(int.Parse).ToArray();        int n = int.Parse(Console.ReadLine());        var sb = new StringBuilder();        long total = 0;        for (int i = 0; i < n; i++)        {            int[] b = Console.ReadLine().Trim().Split('-').Select(int.Parse).ToArray();            // 튜플은 앞 칸부터 비교하지만 C#의 튜플에는 <가 없다 → 칸마다 직접 비교한다            bool beforeBirthday = t[1] < b[1] || (t[1] == b[1] && t[2] < b[2]);            int age = t[0] - b[0] - (beforeBirthday ? 1 : 0);            int fee = (t[1] == b[1] && t[2] == b[2]) ? 0 : Price(age); // 생일 당일은 무료            sb.Append(age).Append(' ').Append(fee).Append('\n');            total += fee;        }        sb.Append(total).Append('\n');        Console.Write(sb);    }}
C++main.cpp · 29 줄
#include <iostream>#include <string>#include <tuple> int price(int age) {    if (age <= 2) return 0;    else if (age <= 12) return 6000;    else if (age <= 18) return 9000;    else if (age <= 64) return 15000;    else return 7000;} int main() {    char dash;    int ty, tm, td, n;    std::cin >> ty >> dash >> tm >> dash >> td >> n;    long long total = 0;    for (int i = 0; i < n; i++) {        int by, bm, bd;        std::cin >> by >> dash >> bm >> dash >> bd;        // std::tie로 묶으면 튜플처럼 앞 칸부터 차례로 비교한다        bool beforeBirthday = std::tie(tm, td) < std::tie(bm, bd);        int age = ty - by - (beforeBirthday ? 1 : 0);        int fee = (tm == bm && td == bd) ? 0 : price(age); // 생일 당일은 무료        std::cout << age << ' ' << fee << '\n';        total += fee;    }    std::cout << total << '\n';}
Cmain.c · 28 줄
#include <stdio.h> int price(int age) {    if (age <= 2) return 0;    else if (age <= 12) return 6000;    else if (age <= 18) return 9000;    else if (age <= 64) return 15000;    else return 7000;} int main(void) {    int ty, tm, td, n;    scanf("%d-%d-%d", &ty, &tm, &td);    scanf("%d", &n);    long total = 0;    for (int i = 0; i < n; i++) {        int by, bm, bd;        scanf("%d-%d-%d", &by, &bm, &bd);        /* 월이 앞서거나, 월이 같고 일이 앞서면 아직 생일 전이다 */        int before_birthday = tm < bm || (tm == bm && td < bd);        int age = ty - by - (before_birthday ? 1 : 0);        int fee = (tm == bm && td == bd) ? 0 : price(age); /* 생일 당일은 무료 */        printf("%d %d\n", age, fee);        total += fee;    }    printf("%ld\n", total);    return 0;}
Craykonmain.cray · 48 줄
날짜(줄){    칸 = 줄.공백제거().나누기("-");    돌려주기 [칸[0].수로변환(), 칸[1].수로변환(), 칸[2].수로변환()];} 요금(age){    만약 (age <= 2)    {        돌려주기 0;    }    아니면 만약 (age <= 12)    {        돌려주기 6000;    }    아니면 만약 (age <= 18)    {        돌려주기 9000;    }    아니면 만약 (age <= 64)    {        돌려주기 15000;    }    돌려주기 7000;} t = 날짜(콘솔.줄읽기());n = 콘솔.줄읽기().수로변환();total = 0;반복 (i = 0; i < n; i++){    b = 날짜(콘솔.줄읽기());    age = t[0] - b[0];    // 월이 앞서거나, 월이 같고 일이 앞서면 아직 생일 전이다    만약 (t[1] < b[1] || t[1] == b[1] && t[2] < b[2])    {        age -= 1;    }    fee = 요금(age);    만약 (t[1] == b[1] && t[2] == b[2])    {        fee = 0; // 생일 당일은 무료    }    콘솔.쓰기(age + " " + fee);    total += fee;}콘솔.쓰기(total);