图论算法(2)--- 如何求DAG中每一个点的所有子孙数量

来源:互联网 发布:科比0506赛季详细数据 编辑:程序博客网 时间:2024/06/05 18:31

问题引入:

上篇文章我们的问题引入中提到了DAG中的LCA定义问题,其实对于节点信息熵,其中的一种定义就是-log(d(node)),d(node)也就是求这个节点的所有子孙数量,那么自然而然,我们就想到了用BFS的思想,由于我们最终要计算信息熵(将在后续文章之图论算法DAG中LCA的算法实现里体现)并根据信息熵决定两个节点之间的相似度,所以对于所有节点我们都给它实际的子孙数量加1,这样就避免了叶子节点子孙数量为0的情况,否则计算信息熵时取log就没有意义。


import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.io.PrintStream;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.LinkedList;import java.util.Map;import java.util.Queue;import java.util.Set;public class DescendentsICCalculator {Map<String, LinkedList<String>> graph;Map<String, Integer> outmap;int total;public DescendentsICCalculator(String path) {String[] strs;String str;total = 0;try {BufferedReader br = new BufferedReader(new FileReader(path));graph = new HashMap<String, LinkedList<String>>();outmap = new HashMap<String,Integer>();while ((str = br.readLine()) != null) {strs = str.split("\\s");if (graph.containsKey(strs[1])) {graph.get(strs[1]).add(strs[0]);} else {LinkedList<String> linkedlist = new LinkedList<String>();linkedlist.add(strs[0]);graph.put(strs[1], linkedlist);}}br.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void computeEachNodeDescendentsNum() {Queue<String> queue;Queue<String> adj;Set<String> visit;Set<String> visitleaf;Set<String> keys = graph.keySet();Iterator<String> it = keys.iterator();int cnt = 0;while (it.hasNext()) {cnt=0;String currentnode = it.next();queue = new LinkedList<String>();adj = new LinkedList<String>();visit = new HashSet<String>();visitleaf = new HashSet<String>();//判断叶子节点queue.add(currentnode);visit.add(currentnode);while (!queue.isEmpty()) {String nextnode = queue.poll();adj = graph.get(nextnode);if (adj == null) {if (!visitleaf.contains(nextnode)) {visitleaf.add(nextnode);outmap.put(nextnode + " ", 1);}continue;}Iterator<String> itadj = adj.iterator();while (itadj.hasNext()) {String neighbor = itadj.next();if (!visit.contains(neighbor)) {queue.add(neighbor);visit.add(neighbor);cnt++;}}}System.out.println(currentnode+ " " +(cnt+1));outmap.put(currentnode, (cnt + 1));}}public Map<String,Integer> getAllDescendentsNum(){return outmap;}public static void main(String[] args) throws IOException {DescendentsICCalculator cal = new DescendentsICCalculator("c:/depthcounter/newdataid.nt");cal.computeEachNodeDescendentsNum();Map<String,Integer> results = cal.getAllDescendentsNum();PrintStream out = new PrintStream("c:/depthcounter/rrrrallDescendentsIdCnt.nt");Iterator<String> it = results.keySet().iterator();while(it.hasNext()){String s = it.next();out.println(s+" "+results.get(s));}out.close();}}


0 0
原创粉丝点击