#include <iostream>
#include <cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<queue>
using namespace std;
const int maxnnode=2000;
const int maxnrow=200;
const int maxncol=2000;
struct node
{
string name;
int size;
bool isdir;
int printrow;
node* parent;
vector<node*> children;
}nodes[maxnnode],*root;
char graph[maxnrow][maxncol];
int nex;
node* newnode(string& name,int size,node* fa)
{
node* p=nodes+nex++;
p->name=name;
p->size=size;
p->isdir=name[0]=='*';
p->parent=fa;
p->children.clear();
return p;
}
void inputchildren(node *p)
{
string name;
int size;
while(cin.get()!='(');
while(cin>>name,name!=")")
{
cin>>size;
p->children.push_back(newnode(name,size,p));
}
}
int work(node* p)
{
if(p->isdir)
{
vector<node*>& v=p->children;
for(int i=0,n=v.size();i<n;i++)
p->size+=work(v[i]);
}
return p->size;
}
//level 控制文件前空格数 row计算文件在第几排。
void gls(node* p,int level,int &row)
{
int offset=level<<3;
if(p->parent)
{
for(int i=p->parent->printrow+1;i<=row;i++)
graph[i][offset]='|';
}
else graph[row][offset]='|';
graph[row][offset+1]='_';
int n=sprintf(&graph[row][offset+2],"%s[%d]",p->name.c_str(),p->size);
graph[row][offset+2+n]='\0';
p->printrow=row++; //row++表示即将进入下一行
if(p->isdir)
{
vector<node*>& v=p->children;
for(int i=0,n=v.size();i<n;i++)
gls(v[i],level+1,row);
}
}
void ls()
{
memset(graph,' ',sizeof(graph));
work(root); //计算大小。
//建树
int row=0;
gls(root,0,row);
for(int i=0;i<row;i++)
puts(graph[i]);
}
bool input()
{
nex=0;
string name;
int size;
if(cin>>name>>size,!cin) return false;
root=newnode(name,size,NULL);
queue<node*> q;
q.push(root);
while(!q.empty())
{
node* p=q.front();q.pop();
if(p->isdir)
{
inputchildren(p);
vector<node*> &v=p->children;
for(int i=0,n=v.size();i<n;i++)
q.push(v[i]);
}
}
return true;
}
int main()
{
while(input()) ls();
return 0;
}
ZOJ 1635(UNIX文件树)(模拟pstree)
最新推荐文章于 2022-09-06 11:49:26 发布