题目描述:
一个文件目录的数据格式为:目录id,本目录中文件大小,(子目录id列表)
其中目录id全局唯一,取值范围[1, 200],本目录中文件大小范围[1, 1000],子目录id列表个数[0,10]例如 : 1 20 (2,3) 表示目录1中文件总大小是20,有两个子目录,id分别是2和3
现在输入一个文件系统中所有目录信息,以及待查询的目录 id ,返回这个目录和及该目录所有子目录的大小之和。
输入描述:
第一行为两个数字M,N,分别表示目录的个数和待查询的目录id,
1 ≤ M ≤ 100
1 ≤ N ≤ 200
接下来M行,每行为1个目录的数据:
目录id 本目录中文件大小 (子目录id列表)
子目录列表中的子目录id以逗号分隔。
输出描述:
待查询目录及其子目录的大小之和
测试用例1:
输入:
3 1
3 15 ()
1 20 (2)
2 10 (3)
输出:45
说明:目录1大小为20,包含一个子目录2 (大小为10),子目录2包含一个子目录3(大小为15),总的大小为20+10+15=45
测试用例2:
输入:
4 2
4 20 ()
5 30 ()
2 10 (4,5)
1 40 ()
输出:60
说明:目录2包含2个子目录4和5,总的大小为10+20+30 = 60
解题思路:
1、使用深度优先搜索来解决,是根据栈实现。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ID_MAX 200
#define CHILD_ID_MAX 10
int main(){
int m,n;
scanf("%d %d",&m,&n);
//定义文件目录数组,子目录数组
int file[ID_MAX];
int child[ID_MAX][CHILD_ID_MAX];
int child_num[ID_MAX];
memset(child_num,0x00,sizeof(int)*ID_MAX);
int id,size;
char str[30];
for(int i = 0;i < m;i++){
scanf("%d %d %s",&id,&size,str);
file[id] = size;
char *p = strtok(str,"() ,");
while(p != NULL){
child[id][child_num[id]++] = atoi(p);
p = strtok(NULL,"() ,");
}
}
//定义栈
int stack[ID_MAX];
//定义栈内元素计数
int top = 0;
//定义收集结果
int res = 0,temp_id;
stack[top++] = n;
while(top > 0){
temp_id = stack[--top];
//把栈顶元素收集到结果中
res += file[temp_id];
for(int i = 0;i < child_num[temp_id];i++){
stack[top++] = child[temp_id][i];
}
}
printf("%d",res);
}