当前位置: 首页 > news >正文

洛谷题目提供**使用面向对象继承概念**的Java解答

洛谷题目提供使用面向对象继承概念的Java解答。每个解答都将展示合理的类层次结构设计。

1. P5740 【深基7.例9】最厉害的学生 (Java OOP 解法)

import java.util.Scanner;// 基类:学生
class Student {protected String name;protected int chinese;protected int math;protected int english;public Student(String name, int chinese, int math, int english) {this.name = name;this.chinese = chinese;this.math = math;this.english = english;}// 计算总分public int getTotal() {return chinese + math + english;}// 获取信息字符串public String getInfo() {return name + " " + chinese + " " + math + " " + english;}
}// 派生类:用于查找最厉害的学生
class TopStudentFinder {private Student topStudent;private int topScore;public TopStudentFinder() {this.topScore = -1;this.topStudent = null;}public void processStudent(Student stu) {int currentScore = stu.getTotal();if (currentScore > topScore) {topScore = currentScore;topStudent = stu;}}public String getTopStudentInfo() {return topStudent != null ? topStudent.getInfo() : "";}
}public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();TopStudentFinder finder = new TopStudentFinder();for (int i = 0; i < n; i++) {String name = sc.next();int chinese = sc.nextInt();int math = sc.nextInt();int english = sc.nextInt();Student stu = new Student(name, chinese, math, english);finder.processStudent(stu);}System.out.println(finder.getTopStudentInfo());sc.close();}
}

2. P5742 【深基7.例11】评等级 (Java OOP 解法)

import java.util.Scanner;// 基类:学生
class Student {protected int id;protected int academic;  // 学业成绩protected int quality;   // 素质拓展成绩public Student(int id, int academic, int quality) {this.id = id;this.academic = academic;this.quality = quality;}// 计算综合分数(避免浮点误差)public int getCompositeScore() {return academic * 7 + quality * 3; // 相当于 (academic*0.7 + quality*0.3) * 10}// 计算总分public int getTotalScore() {return academic + quality;}
}// 派生类:带评级功能的学生
class RatedStudent extends Student {public RatedStudent(int id, int academic, int quality) {super(id, academic, quality);}// 判断是否优秀public boolean isExcellent() {return getTotalScore() > 140 && getCompositeScore() >= 800;}// 获取评级结果public String getRating() {return isExcellent() ? "Excellent" : "Not excellent";}
}public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();for (int i = 0; i < n; i++) {int id = sc.nextInt();int academic = sc.nextInt();int quality = sc.nextInt();RatedStudent student = new RatedStudent(id, academic, quality);System.out.println(student.getRating());}sc.close();}
}

3. P1093 [NOIP2007 普及组] 奖学金 (Java OOP 解法)

import java.util.*;// 基类:学生
class Student {protected int id;protected int chinese;protected int math;protected int english;protected int total;public Student(int id, int chinese, int math, int english) {this.id = id;this.chinese = chinese;this.math = math;this.english = english;this.total = chinese + math + english;}public int getId() { return id; }public int getTotal() { return total; }public int getChinese() { return chinese; }
}// 派生类:可比较的学生(用于排序)
class ComparableStudent extends Student implements Comparable<ComparableStudent> {public ComparableStudent(int id, int chinese, int math, int english) {super(id, chinese, math, english);}@Overridepublic int compareTo(ComparableStudent other) {// 先按总分从高到低排序if (this.total != other.total) {return other.total - this.total;}// 总分相同,按语文成绩从高到低排序if (this.chinese != other.chinese) {return other.chinese - this.chinese;}// 总分和语文都相同,按学号从小到大排序return this.id - other.id;}@Overridepublic String toString() {return id + " " + total;}
}public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();List<ComparableStudent> students = new ArrayList<>();for (int i = 1; i <= n; i++) {int chinese = sc.nextInt();int math = sc.nextInt();int english = sc.nextInt();students.add(new ComparableStudent(i, chinese, math, english));}// 排序Collections.sort(students);// 输出前5名for (int i = 0; i < Math.min(5, students.size()); i++) {System.out.println(students.get(i));}sc.close();}
}

4. P5250 【深基17.例5】木材仓库 (Java OOP 解法)

import java.util.*;// 基类:木材
class Wood implements Comparable<Wood> {protected int length;public Wood(int length) {this.length = length;}public int getLength() {return length;}// 用于TreeSet排序@Overridepublic int compareTo(Wood other) {return Integer.compare(this.length, other.length);}@Overridepublic boolean equals(Object obj) {if (this == obj) return true;if (obj == null || getClass() != obj.getClass()) return false;Wood wood = (Wood) obj;return length == wood.length;}@Overridepublic int hashCode() {return Integer.hashCode(length);}
}// 派生类:木材仓库管理
class WoodWarehouse {private TreeSet<Wood> warehouse;public WoodWarehouse() {warehouse = new TreeSet<>();}// 进货操作public String addWood(int length) {Wood wood = new Wood(length);if (warehouse.contains(wood)) {return "Already Exist";}warehouse.add(wood);return null; // 成功添加不需要输出}// 出货操作public String removeWood(int length) {if (warehouse.isEmpty()) {return "Empty";}Wood target = new Wood(length);// 检查是否有正好长度的木材if (warehouse.contains(target)) {warehouse.remove(target);return String.valueOf(length);}// 没有正好长度的,找最接近的Wood floor = warehouse.floor(target); // 小于等于的最大值Wood ceiling = warehouse.ceiling(target); // 大于等于的最小值Wood toRemove = null;if (floor == null) {toRemove = ceiling;} else if (ceiling == null) {toRemove = floor;} else {int diffFloor = length - floor.getLength();int diffCeiling = ceiling.getLength() - length;if (diffFloor < diffCeiling) {toRemove = floor;} else if (diffFloor > diffCeiling) {toRemove = ceiling;} else {// 距离相等,取较短的一根toRemove = floor;}}if (toRemove != null) {int removedLength = toRemove.getLength();warehouse.remove(toRemove);return String.valueOf(removedLength);}return "Empty";}
}public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int m = sc.nextInt();WoodWarehouse warehouse = new WoodWarehouse();for (int i = 0; i < m; i++) {int op = sc.nextInt();int length = sc.nextInt();if (op == 1) {String result = warehouse.addWood(length);if (result != null) {System.out.println(result);}} else if (op == 2) {System.out.println(warehouse.removeWood(length));}}sc.close();}
}

5. P7176 [COCI2014-2015#4] PRIPREME (Java OOP 解法)

import java.util.*;// 基类:讲解任务
class PresentationTask {protected int timeRequired;public PresentationTask(int timeRequired) {this.timeRequired = timeRequired;}public int getTimeRequired() {return timeRequired;}
}// 派生类:时间调度计算器
class ScheduleCalculator {private List<PresentationTask> tasks;public ScheduleCalculator(List<PresentationTask> tasks) {this.tasks = tasks;}// 计算最少需要的时间public long calculateMinTime() {long totalTime = 0;int maxTime = 0;for (PresentationTask task : tasks) {int time = task.getTimeRequired();totalTime += time;if (time > maxTime) {maxTime = time;}}// 核心逻辑:如果最长的任务时间大于其他所有任务时间之和// 那么最小时间就是 2 * maxTime// 否则就是 totalTimeif (maxTime > totalTime - maxTime) {return 2L * maxTime;} else {return totalTime;}}
}public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();List<PresentationTask> tasks = new ArrayList<>();for (int i = 0; i < n; i++) {int time = sc.nextInt();tasks.add(new PresentationTask(time));}ScheduleCalculator calculator = new ScheduleCalculator(tasks);System.out.println(calculator.calculateMinTime());sc.close();}
}

面向对象设计说明:

  1. P5740:使用Student基类和TopStudentFinder处理器类,体现了单一职责原则。
  2. P5742:通过RatedStudent继承Student,添加评级功能,展示了继承的扩展性。
  3. P1093ComparableStudent继承Student并实现Comparable接口,便于排序。
  4. P5250:设计Wood类和WoodWarehouse仓库管理类,使用TreeSet实现自动排序和快速查找。
  5. P7176:通过PresentationTaskScheduleCalculator分离数据与逻辑,提高代码可维护性。
http://www.jsqmd.com/news/375475/

相关文章:

  • P10250 [GESP样题 六级] 下楼梯
  • 图像金字塔介绍(多尺度分析)高斯金字塔(Gaussian Pyramid)、拉普拉斯金字塔(Laplacian Pyramid)
  • 黑马大模型RAG与Agent智能体实战教程LangChain提示词——18、RAG开发——Chain的基础使用(|管道链、RunnableSerializable对象、上一个组件输出为下一个组件输入)
  • 执业药师培训实测排名前三 零基础/在职党避坑必看,附高通过率秘籍 - 品牌测评鉴赏家
  • bk1 - -Klsw
  • 水表流量时序数据建模全流程(含代码与核心解析)
  • 国产时序数据库实战,金仓如何破解电力行业数据困局 - 详解
  • AeBAD航空发动机叶片异常识别分割数据集labelme格式1149张4类别
  • 基于主成分分析和RBF神经网络(PCA+RBF)预测附Matlab代码
  • 2026执业药师培训机构怎么选!选对少走一年弯路|内附避坑指南 - 品牌测评鉴赏家
  • AeBAD航空发动机叶片异常检测数据集VOC+YOLO格式1149张4类别
  • 面向能源系统的深度强化学习算法性能比较及最优调度策略代码实践
  • 微服务安全实战指南:从授权到日志,全面解析核心模式与最佳实践
  • 【机器人】基于RRT算法进行移动机器人的路径规划,并在路径上应用卡尔曼定位不确定性附matlab代码
  • P2057 [SHOI2007] 善意的投票 / [JLOI2010] 冠军调查
  • 暖冬萌娃必备!童装羽绒服深度测评大揭秘 - 品牌测评鉴赏家
  • 2026国内最新天然野生沉香生产厂家top5推荐!广东广州等地优质沉香供应链权威榜单发布,品质纯正选品指南 - 品牌推荐2026
  • 从零实现一个生产级 RAG 语义搜索系统:C++ + ONNX + FAISS 实战
  • 宝妈必冲✨0-16岁童装羽绒服实测|保暖不踩雷,覆盖全年龄段 全预算 - 品牌测评鉴赏家
  • 题解:P15246 [WC2026] 猫和老鼠
  • 【安全测试】5_应用服务器安全性测试 _SQL注入和文件上传漏洞
  • 【系统分析师】7.6 软件产品线
  • P1344 [USACO4.4] 追查坏牛奶 Pollutant Control
  • 电脑控制神器,吾爱出品
  • 基础设施模块化趋势:DeepSeek辅助编写可编程化云基础设施配置代码
  • 【安全测试】4_用户认证安全测试 _认证与会话、暴力破解、权限控制
  • 云原生AI趋势:DeepSeek与云3.0架构协同,提升AI部署性能与可移植性
  • 线下儿童羽绒服大揭秘!宝妈宝爸必看攻略 - 品牌测评鉴赏家
  • 玄晶引擎2.7.6技术拆解+实战略落地:春节前自动化运营能力升级全解析
  • 宝妈必看|6款高性价比儿童羽绒服,保暖不踩坑还省钱 - 品牌测评鉴赏家