POJ 1057 File Mapping 最详细的解题报告
生活随笔
收集整理的這篇文章主要介紹了
POJ 1057 File Mapping 最详细的解题报告
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目來源:POJ 1057 File Mapping
題目大意:像我的電腦那樣顯示文件夾和文件信息,其中在同一級目錄內,文件夾排在文件的前面并且文件夾的順序不變,同一級目錄中文件按字母序排列。文件以‘f’開頭,文件夾以‘d’開頭,‘*’表示一個case的結束,‘#’表示所有輸入內容結束。
?
解題思路:遞歸創建,最后遞歸輸出。算法比較簡單,我就不細說了,具體看代碼:
?
具體算法(java版,可以直接AC)
1 import java.util.*; 2 3 public class Main { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 Node root = null; 7 Node parent = null; 8 String line = ""; 9 int count = 1; 10 do { 11 root = new DirectoryNode("ROOT", null); 12 parent = root; 13 do { 14 line = input.next(); 15 if (line != null && !line.isEmpty()) { 16 line = line.trim(); 17 Node childNode=null; 18 if (line.startsWith("f")) { 19 childNode=new FileNode(line,parent); 20 parent.children.add(childNode); 21 }else if (line.startsWith("d")) { 22 childNode=new DirectoryNode(line,parent); 23 parent.children.add(childNode); 24 parent=childNode; 25 }else if (line.startsWith("]")) { 26 if(parent!=null){ 27 parent=parent.parent; 28 } 29 } 30 } 31 } while (!line.startsWith("*")); 32 System.out.println(String.format("DATA SET %s:", count++)); 33 root.output(); 34 if(!line.startsWith("#")){ 35 System.out.println(); 36 } 37 } while (!line.startsWith("#")); 38 } 39 } 40 41 abstract class Node { 42 public String name; 43 public Node parent; 44 public String prefix; 45 public List<Node> children; 46 47 public Node(String name, Node parent) { 48 this.name = name; 49 this.parent = parent; 50 this.prefix = ""; 51 if (this.parent != null) { 52 this.prefix = this.parent.prefix + this.prefix; 53 } 54 this.children = new ArrayList<Node>(); 55 } 56 57 public void sort() { 58 Collections.sort(this.children, new Comparator<Node>() { 59 public int compare(Node left, Node right) { 60 if (left instanceof DirectoryNode) { 61 return -1; 62 }else{ 63 if (right instanceof FileNode){ 64 return left.name.compareTo(right.name); 65 }else{ 66 return 1; 67 } 68 } 69 } 70 }); 71 } 72 73 public abstract void output(); 74 } 75 76 class FileNode extends Node { 77 78 public FileNode(String name, Node parent) { 79 super(name, parent); 80 } 81 82 @Override 83 public void output() { 84 if (this.parent != null) { 85 this.prefix = this.parent.prefix + this.prefix; 86 } 87 System.out.println(this.prefix + this.name); 88 } 89 } 90 91 class DirectoryNode extends Node { 92 93 public DirectoryNode(String name, Node parent) { 94 super(name, parent); 95 } 96 97 @Override 98 public void output() { 99 if (this.parent != null) { 100 this.prefix = this.parent.prefix + "| "; 101 } 102 System.out.println(this.prefix + this.name); 103 this.sort(); 104 for (Node child : this.children) { 105 child.output(); 106 } 107 } 108 }?
PS:本人比較喜歡設計模式,因此在寫算法的時候也會想用一些設計模式里面的知識,其實在ACM比賽中,這樣是不好的,效率低。
?
如果有哪里不清楚的,可以給我留言!
?
轉載于:https://www.cnblogs.com/pinxiong/p/4001209.html
總結
以上是生活随笔為你收集整理的POJ 1057 File Mapping 最详细的解题报告的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zend framework2 入门实例
- 下一篇: 程序员求职之道(《程序员面试笔试宝典》)