2014-11-16 2 views
0

안녕하세요, 내가 pq로 만드는 모든 노드를 얻으려고합니다. 그래서 나는 huffman 트리를 만들 수 있도록 체중 측면에서 그들을 주문할 수 있고 처음 두 항목 (최소)을 제거 할 수 있습니다. 어떤 바이너리 트리의 전문 버전이 뭐하는 가장 좋은 방법은 무엇입니까? 감사합니다우선 순위 큐에 노드 삽입하기 자바

public class Main { 

    public void main(String[] args) throws IOException { 

     long start = System.currentTimeMillis(); 
     String inputFileName = args[0]; 
     FileReader reader = new FileReader(inputFileName); 
     Scanner in = new Scanner(reader); 

     // read in the data and do the work here 
     // read a line at a time to enable newlines to be detected and allowed for 

     while(in.hasNext()){ 
      CharacterMap<Character, Integer> hashMap = new CharacterMap<Character, Integer>(); 
      char[] chars = scanner.nextLine().toLowerCase().toCharArray(); 
      int c_count = 0; 
      for (Character c : chars) { 
       c_count += 1; 
       if (hashMap.containsKey(c)) { 
        hashMap.put(c, hashMap.get(c) + 1); 
       } else { 
        hashMap.put(c, 1); 
       } 
     } 

      PriorityQueue<Node> pq = new PriorityQueue<Node>(new Comparator<Node>() { 

      for (Map.Entry<Character, Integer> entry : hashMap.entrySet()){ 

       Node n = new Node(); 

       int f = entry.getValue(); 
       String c = entry.getKey(); 
       n.setWeight(f); 
       n.setCharacter(c); 

       n.setLeftChild(null); 
       n.setRightChild(null); 
       pq.add(n); 
      } 

     reader.close(); 

     String outputFileName = args[1]; 
     FileWriter writer = new FileWriter(outputFileName); 
     writer.write("Input file " + inputFileName + " Huffman algorithm\n\n"); 

     // write out the results here 

     long end = System.currentTimeMillis(); 
     writer.write("\nElapsed time: " + (end - start) + " milliseconds"); 
     writer.close(); 
    } 

} 
+0

코드를 빠르게 스캔 한 것처럼 보입니다. 질문이 뭐야? – EJP

+0

일단 노드 인스턴스 변수 중 하나의 무게로 큐를 정렬하는 방법을 모르겠다. –

답변

0

당신이 무게하여 노드를 주문 우선 순위 큐의 자바 구현을 얻고 싶은 경우에, 당신은 당신의 노드 클래스는 "비교"인터페이스를 구현해야한다. 이는 노드 클래스에 "compareTo"메소드를 넣고 중량을 기준으로 비교를 정의하는 것을 의미합니다. 예 :

private static class Node implements Comparable<Node>{ 
    public int compareTo(Node n) { 
     if(this.weight < n.weight){ 
      return -1; 
     }else if(this.weight > n.weight){ 
      return 1; 
     }else 
      return 0; 
    } 
} 
+0

pq.add (n)을 수행하면 노드가 자동으로 순서대로 삽입됩니까? 그래서 내가 할 수있는 pq.remove() 가장 작은 무게를 얻으려면? –

+0

네, 맞습니다. Java의 우선 순위 대기열 구현은 실제로 [힙]입니다 (http://en.wikipedia.org/wiki/Heap_%28data_structure%29). 따라서 항목이 추가되면 부모/자식과 비교되고 올바른 위치에 "버블 링"됩니다. – Highway62