/*
前面在复习集合框架,看到测试题首先想到用Map存数据,这个代码还未测试结果,希望可以抛砖引玉,跟大家一块交流想法,有错误的话希望大家批评指正。
* 阿里巴巴的ODPS大数据处理平台可以启动一系列并发的作业,每个作业中存在一系列存在父子关系的任务。 * 每个任务用一个三元组表示--(任务id,父任务id,执行开销),其中任务id是一个正整数(>0);父任务id为0表示根任务, * 每个作业存在一个唯一的根任务,并且,所有的任务,如果其父任务id不为0,那么必然是一个已经存在的根任务id; * 执行开销是一个正整数(>0)。系统中至少存在一个作业。 举例如下: (1, 0, 2) (2, 0, 3) (3, 1, 2) (4, 1, 3) 对应的任务关系是: 1(2) 2(3) / \ 3(2) 4(3) 注:括号内的数字表示任务开销。 很容易看出来,这些任务树构成了一个森林。每颗任务树有若干个叶子节点,从根节点到叶子结点的路径上所有的执行开销, 称作叶子节点对应任务的总开销。例如上面一共有3个叶子节点任务,分别是任务3, 4和2,对应的总开销分别是4, 5和3。 总开销最大的叶子节点任务是4,对应的总开销是5。 现在需要编写程序,针对输入的任务数据,找到总开销最大的叶子节点任务对应的总开销,比如针对上面例子,输出5。 编译器版本: Java 1.8.0_66 请使用标准输入输出(System.in, System.out);已禁用图形、文件、网络、系统相关的操作,如java.lang.Process , javax.swing.JFrame , Runtime.getRuntime;不要自定义包名称,否则会报错,即不要添加package answer之类的语句;您可以写很多个类,但是必须有一个类名为Main,并且为public属性,并且Main为唯一的public class,Main类的里面必须包含一个名字为'main'的静态方法(函数),这个方法是程序的入口 时间限制: 3S (C/C++以外的语言为: 5 S) 内存限制: 128M (C/C++以外的语言为: 640 M) 输入: 输入数据包含若干行,每行是用空格分隔的三个十进制整数,空行或者单个整数0代表输入结束 输出: 一个整数 输入范例: 1 0 2 2 0 3 3 1 2 4 1 3 0 输出范例: 5 */ //定义一个数据结构,作为map的Value使用 class Value{ private int id; private int parent; private int cost; public Value(int id,int parent,int cost) { this.id = id; this.parent = parent; this.cost = cost; // TODO Auto-generated constructor stub } public int getParent() { return parent; } public void setParent(int parent) { this.parent = parent; } public int getCost() { return cost; } public void setCost(int cost) { this.cost = cost; } public int getId() { return id; } public void setId(int id) { this.id = id; } } public class Main { static Map<Integer, Value> map = new HashMap<Integer, Value>(); public static void main(String[] args) { ArrayList<Integer> _ids = new ArrayList<Integer>(); ArrayList<Integer> _parents = new ArrayList<Integer>(); ArrayList<Integer> _costs = new ArrayList<Integer>(); Scanner in = new Scanner(System.in); String line = in.nextLine(); while(line != null && !line.isEmpty()) { if(line.trim().equals("0")) break; String []values = line.trim().split(" "); if(values.length != 3) { break; } _ids.add(Integer.parseInt(values[0])); _parents.add(Integer.parseInt(values[1])); _costs.add(Integer.parseInt(values[2])); Value value = new Value(Integer.parseInt(values[0]),Integer.parseInt(values[1]),Integer.parseInt(values[2])); map.put(Integer.parseInt(values[0]), value); line = in.nextLine(); } int res = resolve(_ids, _parents, _costs); System.out.println(String.valueOf(res)); } // write your code here public static int resolve(ArrayList<Integer> ids, ArrayList<Integer> parents, ArrayList<Integer> costs) { int max = 0; for (int i = 0; i < ids.size(); i++) { int groupMax = getMax(map.get(ids.get(i))); max = groupMax>max?groupMax:max; } return max; } //递归求取从每个节点到根节点路径值 public static int getMax(Value value){ int parent = value.getParent(); if(parent==0){ return value.getCost(); } return getMax(map.get(parent))+value.getCost(); } }