PTA 7-9 目录树
在ZIP归档文件中,保留着所有压缩文件和目录的相对路径和名称。当使用WinZIP等GUI软件打开ZIP归档文件时,可以从这些信息中重建目录的树状结构。请编写程序实现目录的树状结构的重建工作。
#include #include #include #include #include #include using namespace std;struct Node { int judge;//是否有/ char s[500]; int cnt; Node *child[500]; Node(int x, char *str) : judge(x), cnt(0) { strcpy(s, str); }};struct Help { int judge; char s[500]; Node *id = NULL; bool operator < (const Help &temp) const { int ans = strcmp(s, temp.s); if (judge != temp.judge) return judge > temp.judge; if (ans != 0) return ans < 0; }};struct Tree { Node *head = NULL; void Init() { head = new Node(1, "root"); } void Insert(char *str) { int len = strlen(str); Node *root = head; char s[500]; int cnt = 0; for (int i = 0; i < len; i++) { if (str[i] == '\\') { s[cnt] = '\0'; bool exist = false; Node *temp = NULL; for (int i = 0; i < root->cnt; i++) { Node *child = root->child[i]; if (strcmp(child->s, s) == 0) { exist = true; temp = child; break; } } if (!exist) temp = root->child[(root->cnt)++] = new Node(1, s); root = temp; cnt = 0; } else s[cnt++] = str[i]; } if (cnt != 0) { s[cnt] = '\0'; bool exist = false; for (int i = 0; i < root->cnt; i++) { Node *child = root->child[i]; if (strcmp(child->s, s) == 0) { exist = true; break; } } if (!exist) root->child[(root->cnt)++] = new Node(0, s); } } void output(Node *root, int depth) { for (int i = 0; i < depth; i++) printf(" "); printf("%s\n", root->s); Help help[500]; for (int i = 0; i < root->cnt; i++) { Node *child = root->child[i]; help[i].id = child; help[i].judge = child->judge, strcpy(help[i].s, child->s); } sort(help, help + (root->cnt)); for (int i = 0; i < root->cnt; i++) { output(help[i].id, depth + 1); } }}tree;int main() { tree.Init(); int n; scanf("%d", &n); getchar(); char str[500]; for (int i = 0; i < n; i++) { gets(str); tree.Insert(str); } tree.output(tree.head, 0); return 0;}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~