import java.util.*;
/**
* Created by handsome.guy on 2014/12/6.
*/
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
scanner.useDelimiter("(\\s+)|(:\\()|(\\)\\s+)");
while(scanner.hasNext()){
int nodeNum=scanner.nextInt();
Map<Integer,List<Integer>> adjMap=new HashMap<Integer, List<Integer>>();
Integer rootName=null;
for(int i=0;i<nodeNum;++i){
int node=scanner.nextInt();
if(rootName==null){
rootName=node;
}
int adjNum=scanner.nextInt();
List<Integer> nodes=new ArrayList<Integer>(adjNum);
for(int j=0;j<adjNum;++j){
nodes.add(scanner.nextInt());
}
adjMap.put(node,nodes);
}
Node root=TreeFactory.parseTree(adjMap,rootName);
System.out.println(Work.calculate(root));
}
}
private static class Work{
public static int calculate(Node root){
postTraversal(root);
return root.getMinSentinel();
}
public static void postTraversal(Node root){
List<Node> children=root.getChildren();
if(children==null || children.isEmpty()){
return;
}
for(Node node:children){
postTraversal(node);
}
int rootFilledResult=1;
for(Node node:children){
rootFilledResult+=node.getMinSentinel();
}
int rootEmptyResult=children.size();
for(Node node:children){
List<Node> subChildren=node.getChildren();
for(Node n:subChildren){
rootEmptyResult+=n.getMinSentinel();
}
}
int min=rootFilledResult<rootEmptyResult?
rootFilledResult:rootEmptyResult;
root.setMinSentinel(min);
return;
}
}
private static class TreeFactory{
public static Node parseTree(Map<Integer,List<Integer>>adjMap,Integer rootName){
Map<Integer,Node> allNode=new HashMap<Integer, Node>();
for(Integer key:adjMap.keySet()){
Node t=new Node();
t.setName(key);
t.setChildren(new ArrayList<Node>());
t.setMinSentinel(0);
allNode.put(key,t);
}
for(Integer key:adjMap.keySet()){
List<Integer> list=adjMap.get(key);
for(Integer name:list){
allNode.get(key).getChildren().add(allNode.get(name));
}
}
return allNode.get(rootName);
}
}
private static class Node{
private Integer name;
private List<Node> children;
private Integer minSentinel;
public Integer getName() {
return name;
}
public void setName(Integer name) {
this.name = name;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public Integer getMinSentinel() {
return minSentinel;
}
public void setMinSentinel(Integer minSentinel) {
this.minSentinel = minSentinel;
}
}
}
杭电1054-后续遍历解决
最新推荐文章于 2020-05-27 13:10:47 发布