【JAVA】 PAT 1092 最好吃的月饼(测试点4超时)

本文介绍了一种通过销量数据评选最好吃月饼的算法。输入包括月饼种类和各城市销量,输出销量最高月饼及其并列冠军。算法使用自定义类存储月饼信息,并按销量和ID排序。

【JAVA】 PAT 1092 最好吃的月饼(测试点4超时)


题目链接
月饼是久负盛名的中国传统糕点之一,自唐朝以来,已经发展出几百品种。

在这里插入图片描述

若想评比出一种“最好吃”的月饼,那势必在吃货界引发一场腥风血雨…… 在这里我们用数字说话,给出全国各地各种月饼的销量,要求你从中找出销量冠军,认定为最好吃的月饼。

输入格式:
输入首先给出两个正整数 N(≤1000)和 M(≤100),分别为月饼的种类数(于是默认月饼种类从 1 到 N 编号)和参与统计的城市数量。

接下来 M 行,每行给出 N 个非负整数(均不超过 1 百万),其中第 i 个整数为第 i 种月饼的销量(块)。数字间以空格分隔。

输出格式:
在第一行中输出最大销量,第二行输出销量最大的月饼的种类编号。如果冠军不唯一,则按编号递增顺序输出并列冠军。数字间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

5 3
1001 992 0 233 6
8 0 2018 0 2008
36 18 0 1024 4

输出样例:

2018
3 5

创建一个类储存月饼的编号和销量,并规定按销量和id排序。

static class mk implements Comparable<mk> {
	int id;
	int xl;
	mk(int i, int x) {
		id = i;
		xl = x;
	}

	@Override
	public int compareTo(mk o) {
		if (this.xl == o.xl) {
			return this.id - o.id;
		}
		return o.xl - this.xl;
	}
}

完整代码(测试点4超时)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;

public class Main {
	public static void main(String[] args) throws Exception {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		StreamTokenizer in = new StreamTokenizer(bf);
		in.nextToken();
		int N = (int) in.nval;
		in.nextToken();
		int M = (int) in.nval;
		mk[] m = new mk[N];

		for (int i = 0; i < M; i++) {
			if (i == 0) {
				for (int j = 0; j < N; j++) {
					in.nextToken();
					int x = (int) in.nval;
					m[j] = new mk(j + 1, x);
				}
			} else {
				for (int j = 0; j < N; j++) {
					in.nextToken();
					int x = (int) in.nval;
					m[j].xl += x;
				}
			}
		}
		Arrays.sort(m);
		long max = m[0].xl;
		out.println(max);
		out.print(m[0].id);
		for (int i = 1; i < N; i++) {
			if (m[i].xl == max) {
				out.printf(" %d", m[i].id);
        continue;
			} else {
				break;
			}
		}
		out.flush();
	}

	static class mk implements Comparable<mk> {
		int id;
		int xl;

		mk(int i, int x) {
			id = i;
			xl = x;
		}

		@Override
		public int compareTo(mk o) {
			if (this.xl == o.xl) {
				return this.id - o.id;
			}
			return o.xl - this.xl;
		}
	}
}

### PAT 1095 解码准考证 测试点4 超时优化 针对PAT乙级真题中的 `1095 解码PAT准考证` 的测试点4超时问题,可以通过以下策略来优化算法性能。 #### 数据存储与处理优化 为了减少不必要的重复计算并提高效率,在数据读取阶段可以预先解析准考证号的信息,并将其分类存储到合适的数据结构中。例如,对于不同类型的查询需求(按等级、考场号或日期),可分别构建对应的哈希表或其他索引结构以便快速查找[^1]。 ```python from collections import defaultdict def preprocess(records): level_map = defaultdict(list) room_map = defaultdict(lambda: {'count': 0, 'total_score': 0}) date_map = defaultdict(dict) for record in records: id_, score = record.split() level, room_id, exam_date, _ = decode_pat_id(id_) # 构建level_map用于查询一 level_map[level].append((id_, int(score))) # 更新room_map用于查询二 room_key = f"{level}-{room_id}" if room_key not in room_map: room_map[room_key]['students'] = [] room_map[room_key]['students'].append(int(score)) room_map[room_key]['count'] += 1 room_map[room_key]['total_score'] += int(score) # 构建date_map用于查询三 if exam_date not in date_map[level]: date_map[level][exam_date] = {} if room_id not in date_map[level][exam_date]: date_map[level][exam_date][room_id] = { 'count': 0, 'total_score': 0 } date_map[level][exam_date][room_id]['count'] += 1 date_map[level][exam_date][room_id]['total_score'] += int(score) return level_map, room_map, date_map ``` 上述代码展示了如何预处理输入记录以支持高效的多维度查询操作[^2]。 #### 查询逻辑调整 在实现具体查询功能时,应充分利用已建立的映射关系而非重新遍历原始数据集。这样能够显著降低时间复杂度至接近O(1)级别[^3]。 ##### 查询一:按等级筛选考生 当接收到指定考试级别的请求时,只需访问对应键值下的列表即可完成排序输出任务。 ```python def query_level(level_map, target_level): candidates = sorted( [(sid, sc) for sid, sc in level_map[target_level]], key=lambda x: (-x[1], x[0]) ) result = "\n".join([f"{cand[0]} {cand[1]}" for cand in candidates]) or "NA" return result ``` ##### 查询二:统计特定考场信息 利用事先准备好的房间字典可以直接获取所需统计数据。 ```python def query_room(room_map, target_room): prefix = "-".join(target_room[:2]) stats = room_map.get(prefix, {}) count = sum(len(stats['students'])) total_scores = sum(stats['students']) avg_score = round(total_scores / max(count, 1)) if count != 0 else 0 output_lines = [ str(count), str(total_scores), *[str(scr) for scr in sorted(stats['students'])], str(avg_score) ] return '\n'.join(output_lines) if count > 0 else "NA" ``` ##### 查询三:汇总某日各场次情况 依据先前整理过的日期关联资料执行相应运算流程。 ```python def query_date(date_map, target_date_info): lvl, dt = target_date_info rooms_data = list(date_map[lvl][dt].items()) ordered_rooms = sorted( rooms_data, key=lambda item: (-item[1]['count'], item[0]) ) lines = [" ".join([ rm_no, str(info['count']), str(info['total_score']) ]) for rm_no, info in ordered_rooms] final_output = "\n".join(lines) if lines else "NA" return final_output ``` 以上函数均基于前期精心设计的数据组织形式运作,从而有效规避了因逐条扫描带来的额外开销问题^.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值