{ }codelper
接口P0199

依次使用的折扣券

对一件初始价格为 P 韩元的商品,按给定顺序一张一张地使用 n 张优惠券。
优惠券有三种。
- "rate p":减去当前价格的 p%。
减去的金额是当前价格 × p ÷ 100 舍去 1 韩元以下部分后的整数。
- "cut k":从当前价格减去 k 韩元。
如果价格会小于 0 韩元,就变成 0 韩元。
- "cap c":如果当前价格高于 c 韩元就变成 c 韩元,否则不变。
第一行给出 P 和 n,接下来 n 行按使用顺序每行给出一张优惠券。
每使用一张优惠券,就输出一行使用后的价格。
试着写一个只有一个方法 apply 的优惠券接口,apply 接收价格并返回使用优惠券后的价格,再让三种优惠券类实现它。
先把所有优惠券放进以优惠券接口为类型的列表,然后依次遍历列表,不问种类只调用 apply。

输入
1 ≤ P ≤ 1,000,000,1 ≤ n ≤ 1,000,0 ≤ p ≤ 100,0 ≤ k, c ≤ 1,000,000(都是整数)
输出
n 行:每使用一张优惠券后的价格
样例 1 · stdin
12345 4
rate 10
cut 2000
cap 8999
rate 50
stdout
11111
9111
8999
4500
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 5 种语言题解

这道题只接受有接口或起接口作用的语法的 Python、TypeScript、Java、C#、C++。
JavaScript 是只要方法名对上就直接调用的鸭子类型,没有地方写接口;C 和 Craykon 没有类。
写下“有 apply”这一约定的方法各语言不同。
TypeScript interface Coupon { apply(price: number): number } 加 class RateCoupon implements Coupon;Java interface Coupon 加 implements(方法必须是 public,本题解用 record 写得更短);C# interface ICoupon(惯例在名字前加 I)加 class RateCoupon : ICoupon;C++ 继承只含纯虚函数 virtual int apply(int) const = 0; 的抽象类,并加上 override。
Python 用 abc.ABC 和 @abstractmethod 写明“必须实现这个方法”(漏写的类在创建对象时抛出 TypeError)。
TypeScript 的接口只在类型检查时存在,运行的代码里会消失。
四个陷阱:① C++ 中基类方法漏写 virtual,通过 Coupon 指针调用时执行的是基类的版本而不是派生类的(静态绑定)。
Java、C# 的接口方法总是调用实现的那一方。
② 在 Java、C#、C++ 中像 price * (p / 100) 那样先除比例,由于是整数除法,p 小于 100 时结果为 0,一点也没减。
要先乘后除。
③ 要舍去的是减去的金额。
如果把剩下的价格 price * (100 - p) / 100 舍去,999 韩元打九折会得到 899 韩元而不是 900 韩元。
④ 用 max(0, …) 防止 cut 让价格变成负数。

Pythonmain.py · 49 行
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 行
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 行
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 行
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 行
#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";    }}