发 ***:
输入:
performance
Adam,125
Andy,110
Bill,92
Evan,154
organization
Aaron,Abel,Adam
Aaron,Abel,Andy
Aaron,Jone,Bill
Aaron,Jone,Evan
eof
Adam,125
Andy,110
Bill,92
Evan,154
organization
Aaron,Abel,Adam
Aaron,Abel,Andy
Aaron,Jone,Bill
Aaron,Jone,Evan
eof
输入的performance表示各个外包人员发***的数量。organization表示经理,组员,外包。这样一种从属关系。其中一个外包人员不会被两个组员管理,一个组员不会被两个经理管理。输出这种管理层级关系,数字表示他手下的***总数。要求按数字从大到小排列,如果数字一样就按名字字典序排列。
输出:
Aaron<481>
-Abel<235>
--Adam<125>
--Andy<110>
-Jone<246>
--Bill<92>
--Evan<154>
-Abel<235>
--Adam<125>
--Andy<110>
-Jone<246>
--Bill<92>
--Evan<154>
思路:建立多叉数,然后三层for循环打印,不过我没有排序;另外输入是个大坑啊,我一直输入没弄好,结束后查了半天终于调好了。用最后那个eof去判断输入是否结束。
排序的话我暂时还没想好,有没有大神帮我改改代码,让我学习一下。
import java.util.*;
/**
* Created by brayden on 2020/9/26 19:02
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<>();
String d=new String();
while (true){
d=sc.nextLine();
if (d.equals("eof"))break;
list.add(d);
}
int per = 0, org = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals("performance")) {
per = i;
}
if (list.get(i).equals("organization")) {
org = i;
}
}
Map<String, Integer> map = new HashMap<>();
for (int i = per + 1; i < org - 1; i++) {
String[] ss = list.get(i).split(",");
map.put(ss[0], Integer.parseInt(ss[1]));
}
TreeNode root = new TreeNode(0, "root");
for (int i = org + 1; i < list.size(); i++) {
String[] orgs = list.get(i).split(",");
if ( root.childs==null||root.getChild(orgs[0]) == null) {
root.childs.add(new TreeNode(0, orgs[0]));
}
if (root.getChild(orgs[0]).childs==null||root.getChild(orgs[0]).getChild("-"+orgs[1]) == null) {
root.getChild(orgs[0]).childs.add(new TreeNode(0, "-" + orgs[1]));
}
if (root.getChild(orgs[0]).getChild("-"+orgs[1]).getChild("--"+orgs[2])==null){
root.getChild(orgs[0]).getChild("-"+orgs[1]).childs
.add(new TreeNode(map.get(orgs[2]),"--"+orgs[2]));
}
}
bfs(root);
print(root);
}
public static int bfs(TreeNode root) {
if (root == null) {
return 0;
}
for (TreeNode child : root.childs) {
root.val += bfs(child);
}
return root.val;
}
public static void print(TreeNode root) {
if (root == null) return ;
for (TreeNode child : root.childs) {
System.out.println(child.name + "<" + child.val + ">");
for (TreeNode o : child.childs) {
System.out.println(o.name + "<" + o.val + ">");
for (TreeNode o2 : o.childs) {
System.out.println(o2.name + "<" + o2.val + ">");
}
}
}
}
}
class TreeNode {
public int val;
public String name;
List<TreeNode> childs;
public TreeNode(int val, String name) {
this.val = val;
this.name = name;
this.childs=new LinkedList<TreeNode>();
}
TreeNode getChild(String name) {
if (this.childs==null)return null;
for (TreeNode child : childs) {
if (child.name.equals(name)) {
return child;
}
}
return null;
}
}

全部评论
(2) 回帖