ZOJ 1635(UNIX文件树)(模拟pstree)

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值