当前位置:网站首页>二叉搜索树解决硬木问题
二叉搜索树解决硬木问题
2022-08-04 20:38:00 【chengqiuming】
一 原问题链接
Hardwood Species - POJ 2418 - Virtual Judgehttps://vjudge.net/problem/POJ-2418
二 输入和输出
1 输入
输入包括每棵树的物种清单,每行一棵树。物种名称不超过 30 个字符,不超过 10 000 种,不超过 1 000 000 棵树。
2 输出
按字母顺序输出植物种群中代表的每个物种的名称,然后是占所有种群的百分比,保留小数点后 4 位。
三 输入和输出样例
1 输入样例
Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow
2 输出样例
Ash 13.7931
Aspen 3.4483
Basswood 3.4483
Beech 3.4483
Black Walnut 3.4483
Cherry 3.4483
Cottonwood 3.4483
Cypress 3.4483
Gum 3.4483
Hackberry 3.4483
Hard Maple 3.4483
Hickory 3.4483
Pecan 3.4483
Poplan 3.4483
Red Alder 3.4483
Red Elm 3.4483
Red Oak 6.8966
Sassafras 3.4483
Soft Maple 3.4483
Sycamore 3.4483
White Oak 10.3448
Willow 3.4483
Yellow Birch 3.4483
四 算法设计
使用二叉搜索树,先将每个单词都存入二叉树中,每出现一次,就修改该单词所在节点 cnt,让它加1,最后通过中序遍历输出结果。
五 代码
package poj2418;
import java.util.Scanner;
public class Poj2418 {
static int sum = 0;
static node rt = new node();
static String w;
// 中序遍历
static void midprint(node root) {//中序遍历
if (root != null) {
midprint(root.l);
System.out.print(root.word);
System.out.printf(" %.4f\n", ((double) root.cnt / (double) sum) * 100);
midprint(root.r);
}
}
// 二叉排序树的插入
static public node insert(node root, String s) {
if (root == null) {
node p = new node(s, 1);
p.l = null;
p.r = null;
root = p;
return root;
}
// 一个临时节点指向根节点,用于返回值
node tmp = root;
node pre = root;
while (root != null) {
// 保存父节点
pre = root;
if (s.compareTo(root.word) > 0) {
root = root.r;
} else if ((s.compareTo(root.word) < 0)) {
root = root.l;
} else {
root.cnt++;
return tmp;
}
}
// 通过父节点添加
if (s.compareTo(pre.word) > 0) {
pre.r = new node(s, 1);
} else {
pre.l = new node(s, 1);
}
return tmp;
}
public static void main(String[] args) {
rt = null; // 一定要初始化
Scanner scanner = new Scanner(System.in);
while (true) {
w = scanner.nextLine();
if (w.equals("##")) {
break;
}
rt = insert(rt, w);
sum++;
}
midprint(rt);
}
}
class node {
String word;
node l;
node r;
int cnt;
public node() {
}
public node(String word, int cnt) {
this.word = word;
this.cnt = cnt;
}
}六 测试
1 输入

2 输出

边栏推荐
猜你喜欢
随机推荐
五分钟入门文本处理三剑客grep awk sed
构建Buildroot根文件系统(I.MX6ULL)
【一起学Rust | 进阶篇 | Service Manager库】Rust专用跨平台服务管理库
Web3安全风险令人生畏,应该如何应对?
STP --- 生成树协议
web 应用开发最佳实践之一:避免大型、复杂的布局和布局抖动
IPV6地址
awk statistical average max min
[TypeScript] In-depth study of TypeScript enumeration
c语言小项目(三子棋游戏实现)
搭建MyCat2一主一从的MySQL读写分离
该如何训练好深度学习模型?
使用 Chrome 开发者工具 coverage 功能分析 web 应用的渲染阻止资源的执行分布情况
Tear down the underlying mechanism of the five JOINs of SparkSQL
漫画 | 老板裁掉我两周后,又把我请回去,工资翻番!
If it is test axi dma catch a few words here
深度解析:为什么跨链桥又双叒出事了?
win10终端中如何切换磁盘
Interviewer: How is the expired key in Redis deleted?
刷题-洛谷-P1304 哥德巴赫猜想









