题目
L2-2 含茶量
ChatGPT(全名:Chat Generative Pre-trained Transformer)近期成为网络讨论的热点话题之一。本题就请你根据某社交网络中发帖的情况,统计每个人帖子中含有 ChatGPT
(不区分大小写)的数量(简称“含茶量”),找出最热衷于讨论这个话题的人,即含茶量排前三的人。
输入格式:
输入在第一行中给出正整数:N(≤104),为参加统计的帖子数量。
随后给出 N 条帖子的信息,每条格式为:第一行给出发帖人 ID,是一个长度不超过 10 位的非空数字串;第二行给出非空的帖子的内容,由不超过 140 个英文字母、数字、空格、标点(只包括 ?
、,
和 .
)组成,以回车结束(回车不算在 140 字内)。
输出格式:
分三行输出含茶量最高的前三个 ID,及其含茶量。有并列时按 ID 的字典序递增输出;如果有含茶量的 ID 不到三个,那么有几个就输出几个,但含茶量为 0 的不要输出。数字间以 1 个空格分隔,行首尾不得有多余空格。
题目保证至少有一个输出。
输入样例:
5
1010
I am not interested in ChatGPT.
233
I am gonna talk about chatgpt, and Chatgpt, and CHATGPT
233
they are all ChatGPT
2
I am gonna talk about chatgpt, and Chatgpt, and CHATGPT
0002
chatgp, hatGPT and Chatppt, are they all ChatGPTs?
输出样例:
233 4
2 3
0002 1
Java代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static String CG = "chatgpt";
static int m, hash[];
// 返回语句含茶量
static int getNum(String s) {
int index = 0, num = 0;
while(index != -1) {
index = s.indexOf(CG);
if(index != -1) {
num++;
s = s.substring(index + 1);
}
}
return num;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Map<String, Integer> map = new HashMap<>(); // 记录总含茶量
while(n -- > 0) {
String id = br.readLine();
String content = br.readLine().toLowerCase(); // 小写评论
int num = getNum(content);
if(map.containsKey(id))
map.put(id, map.get(id) + num);
else
map.put(id, num);
}
Queue<Node> heap = new PriorityQueue<>(); // 优先队列 存储最优三个节点
for(String key : map.keySet()) {
int num = map.get(key);
if(num == 0)
continue;
if(heap.isEmpty() || heap.size() < 3) { // 输出未满
heap.offer(new Node(key, num));
continue;
}
Node node = heap.peek();
if(num > node.num) {
heap.poll();
heap.offer(new Node(key, num));
continue;
}
if(num == node.num && key.compareTo(node.id) < 0) { // key的字典序更小
heap.poll();
heap.offer(new Node(key, num));
}
}
String res = "";
while(!heap.isEmpty()) {
Node node = heap.poll();
if(res == "")
res = node.id + " " + node.num;
else
res = node.id + " " + node.num + "\n" + res;
}
System.out.println(res);
}
}
class Node implements Comparable<Node> {
String id;
int num;
public Node(String id, int num) {
super();
this.id = id;
this.num = num;
}
@Override
public int compareTo(Node o) {
if(this.num == o.num) // 次数相等时
return o.id.compareTo(this.id); // 字典序从大到小排序, 最尾部字典序最大
else
return this.num - o.num; // 次数从小到大排序
}
}