Description
Input
Output
题目大意:模拟一个CMD的运行,假定所有给定的语句都是正确的。
思路:丧心病狂模拟题系列。注意细节,比如我用一个目录dir两次,不要同一个文件算两次,再如有A\B,我删掉了B,然后再删A的时候,不要再把B的容量给算上了。我觉得这题样例还算有良心,我过了样例就AC了o(╯□╰)o
PS:我的代码虽然暴力是暴力了点,不过丧心病狂模拟题的重点,不是要快,而是要好写,好调,准确……
代码(0MS):
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <algorithm> 5 using namespace std; 6 7 const int MAXN = 1000000; 8 9 struct Node { 10 char name[55]; 11 int next, pre, siz; 12 bool isFile, del; 13 }; 14 15 Node a[MAXN]; 16 int head[MAXN], ecnt, root, now; 17 char s[110], tmp[110]; 18 19 void clear() { 20 root = now = 1; 21 head[root] = 0; 22 ecnt = 2; 23 } 24 25 int new_sub(int cur, char *name, int size, bool isFile) { 26 a[ecnt].pre = cur; 27 strcpy(a[ecnt].name, name); 28 a[ecnt].siz = size; 29 a[ecnt].isFile = isFile; 30 a[ecnt].next = head[cur]; 31 a[ecnt].del = 0; 32 head[ecnt] = 0; 33 return head[cur] = ecnt++; 34 } 35 36 int to_sub(int cur, char *name, int siz = 0, int isFile = 0) { 37 for(int p = head[cur]; p; p = a[p].next) 38 if(strcmp(a[p].name, name) == 0) return p; 39 return new_sub(cur, name, siz, isFile); 40 } 41 42 int get_pre(int cur) { 43 return a[cur].pre; 44 } 45 46 int get_root() { 47 return root; 48 } 49 50 void _strcpy(char *&src, char *tar) { 51 int len = 0; 52 while(*src != '\\' && *src != 0) tar[len++] = *src, ++src; 53 tar[len] = 0; 54 if(*src == '\\') ++src; 55 } 56 57 void cd(char *s) { 58 if(*s == '\\') now = get_root(), ++s; 59 while(*s != 0) { 60 _strcpy(s, tmp); 61 now = to_sub(now, tmp); 62 } 63 } 64 65 int str_to_num(char *s) { 66 int ret = 0; 67 for(int i = 0; s[i]; ++i) 68 ret = ret * 10 + s[i] - '0'; 69 return ret; 70 } 71 72 void dir() { 73 while(gets(s) && *s != '>') { 74 int i = 0; 75 for(i = 0; s[i]; ++i) 76 if(s[i] == ' ') break; 77 if(s[i] != ' ') { 78 to_sub(now, s); 79 } 80 else { 81 s[i] = 0; 82 to_sub(now, s, str_to_num(s + i + 1), 1); 83 } 84 } 85 } 86 87 int dfs_del(int cur) { 88 if(a[cur].del) return 0; 89 a[cur].del = true; 90 int ret = 0; 91 for(int p = head[cur]; p; p = a[p].next) { 92 if(a[p].isFile) ret += a[p].siz; 93 else ret += dfs_del(p); 94 } 95 return ret; 96 } 97 98 void deltree(char *s) { 99 if(*s == '\\') now = root, ++s; 100 int cur = now; 101 while(*s != 0) { 102 _strcpy(s, tmp); 103 cur = to_sub(cur, tmp); 104 } 105 printf("%d\n", dfs_del(cur)); 106 } 107 108 int main() { 109 clear(); 110 gets(s); 111 while(strcmp(s, ">exit") != 0) { 112 if(s[0] == 0) {//next exploration 113 clear(); 114 gets(s); 115 } 116 if(strcmp(s, ">cd ..") == 0) { 117 now = get_pre(now); 118 gets(s); 119 continue; 120 } 121 if(strncmp(s, ">cd", 3) == 0) { 122 char *name = s + 4; 123 while(*name == ' ') ++name; 124 cd(name); 125 gets(s); 126 continue; 127 } 128 if(strcmp(s, ">dir") == 0) { 129 dir(); 130 continue; 131 } 132 if(strncmp(s, ">deltree", 8) == 0) { 133 char *name = s + 8; 134 while(*name == ' ') ++name; 135 deltree(name); 136 gets(s); 137 continue; 138 } 139 } 140 }