{ }codelper
接口泛型P0081

通用的最大值

写一个有面积的图形接口,让长方形类和直角三角形类实现它。
然后写一个在列表中找最大项的泛型函数,并把它同时用于整数列表、单词列表和图形列表。
若有多个最大项,选列表中最靠前的那个。
输入分五部分:整数个数 n,n 个整数(一行),单词个数 m,m 个单词(一行),图形个数 k,以及 k 行图形。
图形行为 "rect w h"(宽 w、高 h 的长方形,面积 w × h)或 "tri b h"(底 b、高 h 的直角三角形,面积 b × h ÷ 2)。
输出三行:最大的整数,按字典序排在最后的单词,以及面积最大的图形的 "编号 图形行"(编号是从 1 开始的输入顺序,图形行按输入原样)。

输入
1 ≤ n, m, k ≤ 1000。
-1,000,000,000 ≤ 整数 ≤ 1,000,000,000。
单词为 1 到 10 个小写英文字母。
1 ≤ w, h, b ≤ 10,000(整数)
输出
三行
样例 1 · stdin
4
9 10 -3 10
3
banana apple cherry
3
rect 2 2
tri 3 3
tri 9 1
stdout
10
cherry
2 tri 3 3
main.py
输入(stdin)

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

$ 就绪

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

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

本题只接受有接口和泛型的 TypeScript、Java、C#(Python、JS 不写类型,所以没有单独的泛型;C 两者都没有;C++ 模板的写法差别很大,本题不收)。
三种语言用不同方式表达"可以互相比较的 T"。
Java <T extends Comparable<? super T>>、C# where T : IComparable<T> 给类型加约束,图形接口继承 Comparable<Shape> / IComparable<IShape>,只定义一次按面积比较的方法(Java 的 default 方法,C# 8 的接口默认实现)。
Java 不能用 List<int>,要用 List<Integer>。
TS 的数字和字符串没有比较方法,所以像 argMax<T>(items: T[], compare: (a: T, b: T) => number) 那样一并接收比较函数更自然。
陷阱:TS 中若不用 Number() 转换,直接用 < 比较字符串形式的数字,就会按字符串顺序,例如 "9" > "10"(类型写成 T 时编译器也查不出来)。
用整数除法 b * h / 2 求三角形面积,4.5 会被截成 4,与面积为 4 的长方形相等。
改用面积的两倍 b * h 比较,就只需整数。
面积相同时要选前面的,只在 > 0 时替换;写成 >= 0 会选最后一个。
C# string 的 CompareTo 按区域文化规则比较(纯编码顺序用 string.CompareOrdinal),但本题只有小写字母,结果相同。

TypeScriptmain.ts · 45 行
import { readFileSync } from "node:fs"; interface Shape {  twiceArea(): number; // 넓이의 두 배(삼각형도 정수로 비교하려고)  describe(): string;} class Rect implements Shape {  private w: number;  private h: number;  constructor(w: number, h: number) { this.w = w; this.h = h; }  twiceArea(): number { return 2 * this.w * this.h; }  describe(): string { return `rect ${this.w} ${this.h}`; }} class Tri implements Shape {  private b: number;  private h: number;  constructor(b: number, h: number) { this.b = b; this.h = h; }  twiceArea(): number { return this.b * this.h; }  describe(): string { return `tri ${this.b} ${this.h}`; }} // 가장 큰 것의 자리(같으면 앞의 것). T가 무엇이든 비교 방법만 받으면 된다function argMax<T>(items: T[], compare: (a: T, b: T) => number): number {  let best = 0;  for (let i = 1; i < items.length; i++) if (compare(items[i], items[best]) > 0) best = i;  return best;} const lines: string[] = readFileSync(0, "utf8").split("\n");const nums: number[] = lines[1].trim().split(" ").map(Number);const words: string[] = lines[3].trim().split(" ");const k: number = Number(lines[4]);const shapes: Shape[] = [];for (let i = 0; i < k; i++) {  const [kind, a, b] = lines[5 + i].trim().split(" ");  shapes.push(kind === "rect" ? new Rect(Number(a), Number(b)) : new Tri(Number(a), Number(b)));} const byOrder = <T>(a: T, b: T): number => (a < b ? -1 : a > b ? 1 : 0);console.log(nums[argMax(nums, (a, b) => a - b)]);console.log(words[argMax(words, byOrder)]);const s = argMax(shapes, (a, b) => a.twiceArea() - b.twiceArea());console.log(`${s + 1} ${shapes[s].describe()}`);
JavaMain.java · 58 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List; interface Shape extends Comparable<Shape> {    int twiceArea(); // 넓이의 두 배(삼각형도 정수로 비교하려고)    String describe();     // 넓이로 비교하는 법을 인터페이스가 한 번만 정한다    default int compareTo(Shape other) { return Integer.compare(twiceArea(), other.twiceArea()); }} class Rect implements Shape {    private final int w, h;    Rect(int w, int h) { this.w = w; this.h = h; }    public int twiceArea() { return 2 * w * h; }    public String describe() { return "rect " + w + " " + h; }} class Tri implements Shape {    private final int b, h;    Tri(int b, int h) { this.b = b; this.h = h; }    public int twiceArea() { return b * h; }    public String describe() { return "tri " + b + " " + h; }} public class Main {    /** 가장 큰 것의 자리(같으면 앞의 것). 서로 비교할 수 있는 T라면 무엇이든. */    static <T extends Comparable<? super T>> int argMax(List<T> items) {        int best = 0;        for (int i = 1; i < items.size(); i++)            if (items.get(i).compareTo(items.get(best)) > 0) best = i;        return best;    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        in.readLine();        List<Integer> nums = new ArrayList<>(); // List<int>는 안 된다        for (String t : in.readLine().trim().split(" ")) nums.add(Integer.parseInt(t));        in.readLine();        List<String> words = List.of(in.readLine().trim().split(" "));        int k = Integer.parseInt(in.readLine().trim());        List<Shape> shapes = new ArrayList<>();        for (int i = 0; i < k; i++) {            String[] p = in.readLine().trim().split(" ");            int a = Integer.parseInt(p[1]), b = Integer.parseInt(p[2]);            shapes.add(p[0].equals("rect") ? new Rect(a, b) : new Tri(a, b));        }         System.out.println(nums.get(argMax(nums)));        System.out.println(words.get(argMax(words)));        int s = argMax(shapes);        System.out.println((s + 1) + " " + shapes.get(s).describe());    }}
C#Main.cs · 61 行
using System;using System.Collections.Generic;using System.Linq; interface IShape : IComparable<IShape>{    int TwiceArea(); // 넓이의 두 배(삼각형도 정수로 비교하려고)    string Describe();     // 넓이로 비교하는 법을 인터페이스가 한 번만 정한다(C# 8의 기본 구현)    int IComparable<IShape>.CompareTo(IShape other) => TwiceArea().CompareTo(other.TwiceArea());} class Rect : IShape{    private readonly int w, h;    public Rect(int w, int h) { this.w = w; this.h = h; }    public int TwiceArea() => 2 * w * h;    public string Describe() => $"rect {w} {h}";} class Tri : IShape{    private readonly int b, h;    public Tri(int b, int h) { this.b = b; this.h = h; }    public int TwiceArea() => b * h;    public string Describe() => $"tri {b} {h}";} class Program{    // 가장 큰 것의 자리(같으면 앞의 것). 서로 비교할 수 있는 T라면 무엇이든    static int ArgMax<T>(List<T> items) where T : IComparable<T>    {        int best = 0;        for (int i = 1; i < items.Count; i++)            if (items[i].CompareTo(items[best]) > 0) best = i;        return best;    }     static void Main()    {        Console.ReadLine();        var nums = Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToList();        Console.ReadLine();        var words = Console.ReadLine().Trim().Split(' ').ToList();        int k = int.Parse(Console.ReadLine());        var shapes = new List<IShape>();        for (int i = 0; i < k; i++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            int a = int.Parse(p[1]), b = int.Parse(p[2]);            shapes.Add(p[0] == "rect" ? new Rect(a, b) : new Tri(a, b));        }         Console.WriteLine(nums[ArgMax(nums)]);        Console.WriteLine(words[ArgMax(words)]);        int s = ArgMax(shapes);        Console.WriteLine($"{s + 1} {shapes[s].Describe()}");    }}