{ }codelper
interfacesP0199

Coupons used in order

You use n coupons, one at a time in the given order, on an item whose starting price is P won. There are three kinds of coupons. - "rate p": take p% off the current price.
The amount taken off is current price × p ÷ 100 with everything below 1 won dropped. - "cut k": take k won off the current price.
If the price would go below 0 won, it becomes 0 won. - "cap c": if the current price is more than c won it becomes c won; otherwise it stays. The first line gives P and n, and the next n lines give the coupons, one per line, in the order they are used. Each time you use a coupon, print the price after it, one per line. Write a coupon interface with a single method apply that takes a price and returns the price after the coupon, and have three coupon classes implement it. Put all the coupons in a list typed by the coupon interface, then go through the list in order and only call apply, without asking which kind each coupon is.

Input
1 ≤ P ≤ 1,000,000, 1 ≤ n ≤ 1,000, 0 ≤ p ≤ 100, 0 ≤ k, c ≤ 1,000,000 (all integers)
Output
n lines: the price after each coupon is used
Example 1 · stdin
12345 4
rate 10
cut 2000
cap 8999
rate 50
stdout
11111
9111
8999
4500
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 · 5 languages

This problem accepts only Python, TypeScript, Java, C# and C++, which have interfaces or syntax that plays that role.
JavaScript uses duck typing (you just call a method if the name matches), so there is nowhere to write an interface, and C and Craykon have no classes.
How you write down the promise "there is an apply" differs by language.
TypeScript interface Coupon { apply(price: number): number } with class RateCoupon implements Coupon; Java interface Coupon with implements (the method must be public; this solution uses record to keep it short); C# interface ICoupon (by convention the name starts with I) with class RateCoupon : ICoupon; C++ inherits from an abstract class that has only the pure virtual function virtual int apply(int) const = 0; and marks overrides with override.
Python writes "you must define this method" with abc.ABC and @abstractmethod (a class that leaves it out raises TypeError when you create an object).
A TypeScript interface exists only for type checking and disappears from the running code.
Four traps: ① In C++, if the base class method lacks virtual, calling through a Coupon pointer runs the base class version, not the derived one (static binding).
Java and C# interface methods always run the implementation.
② In Java, C# and C++, dividing the rate first as in price * (p / 100) uses integer division, so it is 0 whenever p is below 100 and nothing is taken off.
Multiply first, then divide.
③ What gets rounded down is the amount taken off.
Rounding down the remaining price price * (100 - p) / 100 instead turns 10% off 999 won into 899 won instead of 900 won.
④ Guard cut with max(0, …) so the price never goes negative.

Pythonmain.py · 49 lines
import sysfrom abc import ABC, abstractmethod  class Coupon(ABC):    """가격을 받아 쿠폰을 쓴 뒤의 가격을 돌려준다"""     @abstractmethod    def apply(self, price: int) -> int: ...  class RateCoupon(Coupon):    def __init__(self, p: int):        self.p = p     def apply(self, price: int) -> int:        return price - price * self.p // 100  # 깎는 돈의 1원 아래를 버린다  class CutCoupon(Coupon):    def __init__(self, k: int):        self.k = k     def apply(self, price: int) -> int:        return max(0, price - self.k)  class CapCoupon(Coupon):    def __init__(self, c: int):        self.c = c     def apply(self, price: int) -> int:        return min(price, self.c)  KINDS = {"rate": RateCoupon, "cut": CutCoupon, "cap": CapCoupon} lines = sys.stdin.read().split("\n")price, n = map(int, lines[0].split())coupons: list[Coupon] = []for i in range(1, n + 1):    kind, value = lines[i].split()    coupons.append(KINDS[kind](int(value))) out = []for c in coupons:  # 어떤 쿠폰인지 묻지 않고 apply만 부른다    price = c.apply(price)    out.append(price)print("\n".join(map(str, out)))
TypeScriptmain.ts · 49 lines
import { readFileSync } from "node:fs"; // 가격을 받아 쿠폰을 쓴 뒤의 가격을 돌려준다interface Coupon {  apply(price: number): number;} class RateCoupon implements Coupon {  constructor(private readonly p: number) {}  apply(price: number): number {    return price - Math.floor((price * this.p) / 100); // 깎는 돈의 1원 아래를 버린다  }} class CutCoupon implements Coupon {  constructor(private readonly k: number) {}  apply(price: number): number {    return Math.max(0, price - this.k);  }} class CapCoupon implements Coupon {  constructor(private readonly c: number) {}  apply(price: number): number {    return Math.min(price, this.c);  }} function makeCoupon(kind: string, value: number): Coupon {  if (kind === "rate") return new RateCoupon(value);  if (kind === "cut") return new CutCoupon(value);  return new CapCoupon(value);} const lines: string[] = readFileSync(0, "utf8").split("\n");const [first, count] = lines[0].trim().split(/\s+/).map(Number);const coupons: Coupon[] = [];for (let i = 1; i <= count; i++) {  const [kind, value] = lines[i].trim().split(/\s+/);  coupons.push(makeCoupon(kind, Number(value)));} let price = first;const out: number[] = [];for (const c of coupons) {  price = c.apply(price); // 어떤 쿠폰인지 묻지 않고 apply만 부른다  out.push(price);}console.log(out.join("\n"));
JavaMain.java · 55 lines
import java.io.*;import java.util.*; public class Main {    // 가격을 받아 쿠폰을 쓴 뒤의 가격을 돌려준다    interface Coupon {        int apply(int price);    }     record RateCoupon(int p) implements Coupon {        public int apply(int price) {            return price - price * p / 100; // 곱하고 나서 나눈다: 깎는 돈의 1원 아래를 버린다        }    }     record CutCoupon(int k) implements Coupon {        public int apply(int price) {            return Math.max(0, price - k);        }    }     record CapCoupon(int c) implements Coupon {        public int apply(int price) {            return Math.min(price, c);        }    }     static Coupon makeCoupon(String kind, int value) {        return switch (kind) {            case "rate" -> new RateCoupon(value);            case "cut" -> new CutCoupon(value);            default -> new CapCoupon(value);        };    }     public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        StringTokenizer st = new StringTokenizer(br.readLine());        int price = Integer.parseInt(st.nextToken());        int n = Integer.parseInt(st.nextToken());        List<Coupon> coupons = new ArrayList<>();        for (int i = 0; i < n; i++) {            st = new StringTokenizer(br.readLine());            String kind = st.nextToken();            coupons.add(makeCoupon(kind, Integer.parseInt(st.nextToken())));        }         StringBuilder sb = new StringBuilder();        for (Coupon c : coupons) {            price = c.apply(price); // 어떤 쿠폰인지 묻지 않고 apply만 부른다            sb.append(price).append('\n');        }        System.out.print(sb);    }}
C#Main.cs · 60 lines
using System;using System.Collections.Generic;using System.Text; // 가격을 받아 쿠폰을 쓴 뒤의 가격을 돌려준다interface ICoupon{    int Apply(int price);} class RateCoupon : ICoupon{    private readonly int p;    public RateCoupon(int p) { this.p = p; }    public int Apply(int price) => price - price * p / 100; // 곱하고 나서 나눈다: 깎는 돈의 1원 아래를 버린다} class CutCoupon : ICoupon{    private readonly int k;    public CutCoupon(int k) { this.k = k; }    public int Apply(int price) => Math.Max(0, price - k);} class CapCoupon : ICoupon{    private readonly int c;    public CapCoupon(int c) { this.c = c; }    public int Apply(int price) => Math.Min(price, c);} class Program{    static ICoupon MakeCoupon(string kind, int value) => kind switch    {        "rate" => new RateCoupon(value),        "cut" => new CutCoupon(value),        _ => new CapCoupon(value),    };     static void Main()    {        var first = Console.ReadLine()!.Split(' ', StringSplitOptions.RemoveEmptyEntries);        int price = int.Parse(first[0]), n = int.Parse(first[1]);        var coupons = new List<ICoupon>();        for (int i = 0; i < n; i++)        {            var parts = Console.ReadLine()!.Split(' ', StringSplitOptions.RemoveEmptyEntries);            coupons.Add(MakeCoupon(parts[0], int.Parse(parts[1])));        }         var sb = new StringBuilder();        foreach (ICoupon c in coupons)        {            price = c.Apply(price); // 어떤 쿠폰인지 묻지 않고 Apply만 부른다            sb.Append(price).Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 51 lines
#include <algorithm>#include <iostream>#include <memory>#include <string>#include <vector> // C++의 인터페이스: 순수 가상 함수만 가진 추상 클래스struct Coupon {    virtual int apply(int price) const = 0;    virtual ~Coupon() = default; // 기반 포인터로 지워도 파생 소멸자가 불리게}; struct RateCoupon : Coupon {    int p;    explicit RateCoupon(int p) : p(p) {}    int apply(int price) const override { return price - price * p / 100; } // 깎는 돈의 1원 아래를 버린다}; struct CutCoupon : Coupon {    int k;    explicit CutCoupon(int k) : k(k) {}    int apply(int price) const override { return std::max(0, price - k); }}; struct CapCoupon : Coupon {    int c;    explicit CapCoupon(int c) : c(c) {}    int apply(int price) const override { return std::min(price, c); }}; std::unique_ptr<Coupon> makeCoupon(const std::string& kind, int value) {    if (kind == "rate") return std::make_unique<RateCoupon>(value);    if (kind == "cut") return std::make_unique<CutCoupon>(value);    return std::make_unique<CapCoupon>(value);} int main() {    int price, n;    std::cin >> price >> n;    std::vector<std::unique_ptr<Coupon>> coupons;    for (int i = 0; i < n; i++) {        std::string kind;        int value;        std::cin >> kind >> value;        coupons.push_back(makeCoupon(kind, value));    }    for (const auto& c : coupons) {        price = c->apply(price); // 어떤 쿠폰인지 묻지 않고 apply만 부른다        std::cout << price << "\n";    }}