一个文件目录的数据格式为:目录
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
以逗号分隔。
输出描述:
待查询目录及其子目录的大小之和
public class MLSize {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//总数
int sum=in.nextInt();
//待查询目录
int target=in.nextInt();
Map<Integer,Integer> sizeMap=new HashMap<>();
Map<Integer,Integer[]> childMap=new HashMap<>();
while (in.hasNext()){
int index=in.nextInt();
sizeMap.put(index,in.nextInt());
String child=in.next();
String s = child.replace("()","");
//获取子文件目录
if (isNoEmpty(s)){
//对字符串进行处理
String replace1 = s.replace("(", "");
String replace2 = replace1.replace(")", "");
String[] split = replace2.split(",");
Integer[] childIndex=new Integer[split.length];
for (int i=0;i<split.length;i++){
childIndex[i]=Integer.parseInt(split[i]);
}
//写入
childMap.put(index,childIndex);
}
}
int num=0;
num = getSize(sizeMap, target, childMap);
System.out.println(num);
}
/**
* 判断字符串是否有值
*/
public static boolean isNoEmpty(String s){
return s != null && s.length() != 0;
}
/**
* 获取对应index的文件目录数
*/
public static int getSize(Map<Integer,Integer> sizeMap,int target,Map<Integer,Integer[]> childMap){
int sum=sizeMap.get(target);
if (childMap.get(target)!=null){
Integer[] integers = childMap.get(target);
for (Integer integer : integers) {
sum += getSize(sizeMap, integer, childMap);
}
}
return sum;
}
}