Categories:
.NET (961)
C (387)
C++ (185)
CSS (84)
DBA (8)
General (31)
HTML (48)
Java (641)
JavaScript (220)
JSP (109)
JUnit (31)
MySQL (297)
Networking (10)
Oracle (562)
Perl (48)
Perl (9)
PHP (259)
PL/SQL (140)
RSS (51)
Software QA (28)
SQL Server (5)
Struts (20)
Unix (2)
Windows (3)
XHTML (199)
XML (59)
Other Resources:
Calculating Total Weight of Subtree
Subject: Calculating Total Weight of Subtree --- Category: ,1, --- Question
Can you write a computer code for the following problem:
Given a text file with 3 comma-delimited columns of all integers: 'id', 'parent' and 'weight'. Each line represents a node identified by 'id'. 'parent' refers to 'id' of another node. Print out, for each node, the total weight of a subtree below this node.
✍: Guest
Here is the solution in Java:
import java.io.*; import java.util.*; public class PrintWeight { public static void main(String[] a) { Hashtable<String, String> parentMap = new Hashtable<String, String>(); Hashtable<String, Long> weightMap = new Hashtable<String, Long>(); try { BufferedReader input = new BufferedReader(new FileReader(a[0])); String line = null; while ( (line = input.readLine()) != null ) { String[] cols = line.split(","); String id = cols[0].trim(); String parent = cols[1].trim(); long weight = Long.parseLong(cols[2]); Long totalWeight = weightMap.get(id); if (totalWeight==null) { weightMap.put(id, weight); } else { weightMap.put(id, totalWeight.longValue()+weight); } parentMap.put(id, parent); weight = weightMap.get(id).longValue(); while ( parent!=null && parent.length()>0 ) { totalWeight = weightMap.get(parent); if (totalWeight==null) { weightMap.put(parent, weight); } else { weightMap.put(parent, totalWeight.longValue()+weight); } parent = parentMap.get(parent); } } input.close(); } catch (Exception e) { e.printStackTrace(); } Enumeration<String> nodes = weightMap.keys(); while(nodes.hasMoreElements()) { String id = nodes.nextElement(); long weight = weightMap.get(id).longValue(); System.out.println(id+", "+weight); } } }
2014-01-02, 2856👍, 0💬
Popular Posts:
How Large Can a Single Cookie Be? - PHP Script Tips - Understanding and Managing Cookies How large c...
What is continuous and staged representation? CMMI contains 25 key process areas which organization ...
How To Compare Two Strings with strcmp()? - PHP Script Tips - PHP Built-in Functions for Strings PHP...
How can you enable automatic paging in DataGrid ? Following are the points to be done in order to en...
What is difference between custom JSP tags and JavaBeans? Custom JSP tag is a tag you defined. You d...