当日总结

模拟一个简单的文件系统,用二叉树表示目录结构。每个节点代表一个目录或文件,包含名称和大小(目录大小为0)。请实现:
计算目录总大小
查找最大文件
显示目录结构

输入格式:
第一行:整数N,表示节点数量
接下来N行:每行节点ID 名称 大小 左子节点ID 右子节点ID

输出格式:
计算目录总大小
查找最大文件
显示目录树
如下所示:
Total size: X bytes
Largest file: 文件名 (Y bytes)
或如果没有文件
No files found
Directory structure:
缩进文件名/目录名 (大小 bytes/[DIR])

输入样例:
6
1 root 0 2 3
2 documents 0 4 5
3 pictures 0 6 -1
4 file1.txt 100 -1 -1
5 file2.doc 200 -1 -1
6 photo.jpg 1500 -1 -1
输出样例:
Total size: 1800 bytes
Largest file: photo.jpg (1500 bytes)
Directory structure:
root [DIR]
documents [DIR]
file1.txt (100 bytes)
file2.doc (200 bytes)
pictures [DIR]
photo.jpg (1500 bytes)

include

include

include

include<unordered_map>

include<unordered_set>

include

using namespace std;
struct Node{
int id;
string name;
int left;
int right;
int size;
};
void Print(int currId,unordered_map<int,Node>& nodes,int level)
{
if(currId-1)return;
Node& currNode=nodes[currId];
for(int i=0;i<level;i++)
{
cout<<" ";
}
if(currNode.size
0)
{
cout<<currNode.name<<" [DIR]"<<endl;
}else{
cout<<currNode.name<<" ("<<currNode.size<<" bytes)"<<endl;
}
Print(currNode.left,nodes,level+1);
Print(currNode.right,nodes,level+1);
}
int main()
{
int n;
cin>>n;
unordered_map<int,Node>nodes;
unordered_setchildId;
for(int i=0;i<n;i++)
{
Node node;
cin>>node.id>>node.name>>node.size>>node.left>>node.right;
nodes[node.id]=node;
if(node.left!=-1)childId.insert(node.left);
if(node.right!=-1)childId.insert(node.right);
}
int total_size=0;
for(auto& pair:nodes)
{
Node node=pair.second;
total_size+=node.size;
}
cout<<"Total size: "<<total_size<<" bytes"<<endl;
int max_size=INT_MIN;
string fileName="";
for(auto& pair:nodes)
{
Node node=pair.second;
if(node.size>0&&node.size>max_size)
{
max_size=node.size;
fileName=node.name;
}
}
if(max_sizeINT_MIN)
{
cout<<"No files found"<<endl;
}else{
cout<<"Largest file: "<<fileName<<" ("<<max_size<<" bytes)"<<endl;
}
int rootId=-1;
for(auto& pair:nodes)
{
int curId=pair.first;
if(childId.find(curId)
childId.end())
{
rootId=curId;
break;
}
}
cout<<"Directory structure:"<<endl;
Print(rootId,nodes,0);
return 0;
}

posted @ 2025-12-05 17:43  lagranSun  阅读(4)  评论(0)    收藏  举报