POJ1057 FILE MAPPING

题目来源:http://poj.org/problem?id=1057

题目大意:计算机的用户通常希望能够看到计算机存储的文件的层次结构的图形化表示。Microsoft Windows的 "Explorer"(文件浏览器)就是这样的应用。在图形界面出现以前,最好的描述文件层级结构的方法是展示一个目录和文件的“map”,来表示文件的目录结构。例如:

ROOT

| DIR1
| File1
| File2
| File3
| DIR2
| DIR3
| File1
File1
File2

上面的实例展示了一个根目录,包含了两个文件和三个子目录,第一个子目录下包含三个文件。子二个子目录为空,第三个子目录含一个文件。

输入:编写一个程序,读入一系列的数据用于表示一个计算机中的文件结构。每个数据集用一个*号来表示结束。整个数据的结束标记为#。数据集中含多个文件和目录。约定文件结构的起始点是root,每个目录的结尾用']'表示。目录名以'd'开头,文件名以'f'开头。文件名可能有扩展名也可能没有扩展名。文件名和目录名不含空格。

输出:对于每个目录先输出其子目录,然后输出包含的文件,文件按字典序输出,每个数据集首先输出一行"DATA SET x:" ,x为数据集序号,从1开始计。每个测试用例之间用空行隔开。每个层级输出一个‘|’后接5个空格。具体见sample。


Sample Input

file1
file2
dir3
dir2
file1
file2
]
]
file4
dir1
]
file3
*
file2
file1
*
#

Sample Output

DATA SET 1:
ROOT
|     dir3
|     |     dir2
|     |     file1
|     |     file2
|     dir1
file1
file2
file3
file4

DATA SET 2:
ROOT
file1
file2

本题的输出格式要求比较严,要特别小心,另外对于每个目录,文件需要排序,但是对于子目录只需要按出现的顺序输出。

可以递归实现,也可以用栈。代码里用的递归。

 1 ////////////////////////////////////////////////////////////////////
 2 //        POJ1057 FILE MAPPING
 3 //        Memory: 200K        Time: 16MS
 4 //        Language: C++        Result : Accepted
 5 ////////////////////////////////////////////////////////////////////
 6 
 7 #include <iostream>
 8 #include <string>
 9 #include <list>
10 
11 using namespace std;
12 string str;
13 
14 void HandleDir(int layer, string dir_name) {
15     list<string> file_list;    
16     
17     for (int i = 0; i < layer; ++i) {
18         cout << "|     ";
19     }
20     cout << dir_name << endl;
21     while (str != "*" && str != "]") {
22         if (str[0] == 'f') {
23             file_list.push_back(str);
24         }
25         else if (str[0] == 'd') {
26             string dir = str;
27             cin >> str;
28             HandleDir(layer + 1, dir);
29         }
30         cin >> str;
31     }
32     file_list.sort();
33     for (list<string>::iterator it = file_list.begin(); it != file_list.end(); ++it) {
34         for (int i = 0; i < layer; ++i) {
35             cout << "|     ";
36         }
37         cout << *it << endl;
38     }
39 }
40 
41 int main(void) {
42     
43     for (int case_id = 1; cin >> str, str != "#"; ++case_id) {
44         cout << "DATA SET " << case_id << ":" << endl;
45         HandleDir(0, "ROOT");
46         cout << endl;
47     }
48     return 0;
49 }
View Code

 

posted @ 2013-10-28 20:59  小菜刷题史  阅读(237)  评论(0编辑  收藏  举报