Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
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, 3509👍, 0💬
Popular Posts:
Can a variable be both const and volatile? Yes. The const modifier means that this code cannot chang...
Explain all parts of a deployment diagram? Package: It logically groups element of a UML model. Node...
What does a well-written Object Oriented program look like? A well-written object oriented program e...
How To Run "mysql" Commands from a Batch File? - MySQL FAQs - Command-Line End User Interface mysql ...
What will be printed as the result of the operation below: #define swap(a,b) a=a+b;b=a-b;a=a-b; void...