咕咕东的目录管理器(复杂模拟题的普适性方法)

今天学长讲了复杂模拟题的普适性方法,我们在这里以一道例题来解释一下如何将复杂模拟题进行普适性处理,一步一步拆分模拟题。
PS:内容来自讲课ppt

例题:咕咕东的目录管理器

问题描述

咕咕东的雪梨电脑的操作系统在上个月受到宇宙射线的影响,时不时发生故障,他受不了了,想要写一个高效易用零bug的操作系统 —— 这工程量太大了,所以他定了一个小目标,从实现一个目录管理器开始。前些日子,东东的电脑终于因为过度收到宇宙射线的影响而宕机,无法写代码。他的好友TT正忙着在B站看猫片,另一位好友瑞神正忙着打守望先锋。现在只有你能帮助东东!

初始时,咕咕东的硬盘是空的,命令行的当前目录为根目录 root。

目录管理器可以理解为要维护一棵有根树结构,每个目录的儿子必须保持字典序。

现在咕咕东可以在命令行下执行以下表格中描述的命令:

命令类型实现说明
MKDIR s操作在当前目录下创建一个子目录 s,s 是一个字符串创建成功输出 “OK”;若当前目录下已有该子目录则输出 “ERR”
RM s操作在当前目录下删除子目录 s,s 是一个字符串删除成功输出 “OK”;若当前目录下该子目录不存在则输出 “ERR”
CD s操作进入一个子目录 s,s 是一个字符串(执行后,当前目录可能会改变)进入成功输出 “OK”;若当前目录下该子目录不存在则输出 “ERR”,特殊地,若 s 等于 “ . . .. ..” 则表示返回上级目录,同理,返回成功输出 “OK”,返回失败(当前目录已是根目录没有上级目录)则输出 “ERR”
SZ询问输出当前目录的大小也即输出 1+当前目录的子目录数
LS询问输出多行表示当前目录的 “直接子目录” 名若没有子目录,则输出 “EMPTY”;若子目录数属于 [1,10] 则全部输出;若子目录数大于 10,则输出前 5 个,再输出一行 “ . . . ... ...”,输出后 5 个。
TREE询问输出多行表示以当前目录为根的子树的前序遍历结果若没有后代目录,则输出 “EMPTY”;若后代目录数+1(当前目录)属于 [1,10] 则全部输出;若后代目录数+1(当前目录)大于 10,则输出前 5 个,再输出一行 “ . . . ... ...”,输出后 5 个。
UNDO特殊撤销操作撤销最近一个 “成功执行” 的操作(即MKDIR或RM或CD)的影响,撤销成功输出 “OK” 失败或者没有操作用于撤销则输出 “ERR”

Input

输入文件包含多组测试数据,第一行输入一个整数表示测试数据的组数 T (T <= 20);

每组测试数据的第一行输入一个整数表示该组测试数据的命令总数 Q (Q <= 1e5);

每组测试数据的 2 ~ Q+1 行为具体的操作 (MKDIR、RM 操作总数不超过 5000);

面对数据范围你要思考的是他们代表的 “命令” 执行的最大可接受复杂度,只有这样你才能知道你需要设计的是怎样复杂度的系统。

Output

每组测试数据的输出结果间需要输出一行空行。注意大小写敏感。

时空限制

Time limit 6000 ms

Memory limit 1048576 kB

Sample input

1
22
MKDIR dira
CD dirb
CD dira
MKDIR a
MKDIR b
MKDIR c
CD ..
MKDIR dirb
CD dirb
MKDIR x
CD ..
MKDIR dirc
CD dirc
MKDIR y
CD ..
SZ
LS
TREE
RM dira
TREE
UNDO
TREE

Sample output

OK
ERR
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
9
dira
dirb
dirc
root
dira
a
b
c
dirb
x
dirc
y
OK
root
dirb
x
dirc
y
OK
root
dira
a
b
c
dirb
x
dirc
y

解题思路

基本框图

这是一个大型的复杂模拟题,对于这样一个复杂的模拟题,我们应该首先从大局考虑,自顶向下地设计整个框架,先写出函数的接口,内部实现最后再写。首先一个基本的框图可以写出来:

#include <bits/stdc++.h>
using namespace std;
char tmps[20];
void solve()
{
	int n;scanf("%d",&n);//每组数据有n行命令
	while(n--){
		scanf("%d",tmps);
		//一条命令不是单纯的字符串,可能涉及到如何undo,将其封装成Command,以便于复用/扩展
		Command* cmd=new Command(tmps);
		...
	}
}
int main()
{
	int T; scanf("%d",&T);//测试有T组数据
	while(T--) solve();
	return 0;
}
封装

然后我们需要考虑命令有什么,需要我们做什么。由于有的命令有命令参数,比如"MKDIR s",所以我们需要进行参数的分离,同类的信息进行内聚,我们就需要封装Command

struct Command
{
	const string CMDNAMES[7]={"MKDIR","RM","CD","SZ","LS","TREE","UNDO"};
	int type;//命令的类型
	string arg;//命令的参数
	Command(string s){//构造函数
		for (int i=0; i<7; i++){
			if(CMDNAMES[i]==s){
				type=i;
				if(i<3){//前三个都有参数
					scanf("%s",tmps);
					arg=tmps;
					return;;
				}
			}
		}
	}
}
树型结构

然后我们需要考虑的是一棵目录树,这是一个必然的需求。那我们使用什么来维护这棵树?

  • 数据结构上的二叉树?
  • 图论上的多叉树?

我们可以注意到,题目要求根据子目录的名字得到子目录,因此我们可以使用map来处理,使用map<string,目录>,这可以根据key值在内部进行字典序排序,这样每次取到子目录的时间复杂度都是log级别的。
所以我们最终的树结构是这样的:

struct Directory
{
	string name;//当前目录的名字
	map<string ,Directory*> children;//用指针为了避免复制构造造成的内存浪费
	Directory* parent;//便于"CD.."要返回上级目录
	int subtreeSize;//便于“SZ”要输出子树大小
	Directory(string name,Directory* parent){
		this->name=name;
		this->parent=parent;
		this->subtreeSize=1;
	}
}
解题框架

完善后的solve框架如下所示:

void solve()
{
	int n;scanf("%d",&n);
	Directory* now new Directory("root",nullptr);
	while(n--){
		scanf("%s",tmps);
		Command* cmd=new Command(tmps);
		switch(cmd->type){
			case 0: now->mkdir(cmd->arg); break;
			case 1: now->rm(cmd->arg); break;
			case 2: now->cd(cmd->arg); break;
			case 3: now->sz(); break;
			case 4: now->ls(); break;
			case 5: now->tree(); break;
			case 6://UNDO先放在一边
		}
	}
}

我们还要在Directory结构体里面写具体的一些实现:

struct Directory(){
	/*其他部分*/
	Directory* mkdir(string name);
	Directory* rm(string name);
	Directory* cd(string name);
	void sz(); 
	void ls(); 
	void tree();
}

这个时候我们会发现,需要设计返回值来告知某条命令是否执行成功。

其次,UNDO指令我们没有办法封装在一个Directory内部,因为这条指令是隶属于当前测试的数据环境。所以我们需要将执行成功的命令存起来,以便于"UNDO"

UNDO指令执行有两个前提条件:1. 必须是MKDIR,RM,CD命令中的一种。2. 必须已经执行成功

因此我们需要保存每条指令的执行结果,以便于那三种情况的回退

struct Command
{
	/*其他*/
	Directory* tmpDir;//记录刚刚操作设计的目录节点
}

下面对solve函数进行填充:

void solve()
{
	int n;scanf("%d",&n);
	Directory* now=new Directory("root",nullptr);
	vector<Command*> cmdList;//新增加的数组,用来存成功执行的命令以便于"UNDO"
	while(n--){
		scanf("%s",tmps);
		Command* cmd=new Command(tmps);
		switch(cmd->type){
			case:0:case 1://MKDIR,RM
				cmd->tmpDir=cmd->type==0 ? now->mkdir(cmd->arg) : now->rm(cmd->arg);
				if(cmd->tmpDir==nullptr) printf("ERR\n");
				else {
					printf("OK\n");
					cmdList.push_back(cmd);
				}
				break;
			case 2:
				Directory* ch=now->cd(cmd->arg);
				if(ch==nullptr) printf("ERR\n");
				else {
					printf("OK\n");
					cmd->tmpDir=now; 
					now=ch;
					cmdList.push_back(cmd);
				}	
				break;
			case 3: now->sz(); break;
			case 4: now->ls(); break;
			case 5: now->tree(); break;
			case 6:{
				bool success=false;//用来记录UNDO是否执行成功
				while(!success && !cmdList.empty()){
					cmd=cmdList.back(); cmdList.pop_back();
					switch(cmd->type){
						case 0: success=now->rm(cmd->arg)!=nullptr; break;//undo MKDIR
						case 1: success=now->addChild(cmd->tmpDir); break;//undo RM
						case 2: now=cmd->tmpDir; success=true; break;//undo CD
					}
				}
				printf(success ? "OK\n" : "ERR\n");
			}
		}
	}
}
细节处理

需要注意的是,到目前为止,很多函数仍然只是接口,并没有内部实现,现在整体框架已经定下了,可以写一些细节了,接下来逐一实现Directory的子函数

struct Directory
{
    string name;//当前目录的名字
    map<string ,Directory*> children;//用指针为了避免复制构造造成的内存浪费
    Directory* parent;//便于"CD.."要返回上级目录
    int subtreeSize;//便于“SZ”要输出子树大小
    Directory(string name,Directory* parent){
        this->name=name;
        this->parent=parent;
        this->subtreeSize=1;
    }
public:
	Directory* getChild(string name){//取得子目录并返回,不存在就返回空指针
		auto it =children.find(name);
		if(it==children.end()) return nullptr;
		else return it->second;
	}
	Directory* mkdir(string name){//创建子目录并返回,创建失败返回空指针
		if(children.find(name) != children.end()) return nullptr;
		Directory* ch=new Directory(name,this);
		children[name]=ch;
		maintain(+1);
		return ch;
	}
	Directory* rm(string name){//删除子目录并返回,删除失败则返回空指针
        auto it=children.find(name);
        if(it==children.end()) return nullptr;
        maintain(-1*it->second->subtreeSize);
        children.erase(it);
        return it->second;
    }
	Directory* cd(string name){
		if(name=="..") return this->parent;
		return getChild(name);
	}
	bool addChild(Directory* ch){//加入子目录并返回成功与否
		if(children.find(ch->name)!=children.end()) return false;
		children[ch->name]=ch;
		maintain(+ch->subtreeSize);
		return true;
	}
	void maintain(int delta){//向上维护子树的大小,便于实现"SZ"
		updated=true;
		subtreeSize+=delta;
		if(parent!=nullptr) parent->maintain(delta);
	}
	void sz(){
		printf("%d\n",this->subtreeSize);
	}
	void ls(){
		int sz=children.size();
		if(sz==0) printf("EMPTY\n");
		else if(sz<=10){
			for (auto &entry : children)
				printf("%s\n",entry.first.c_str());
		}
		else {
			auto it=children.begin();
			for (int i=0; i<5; i++,it++) printf("%s\n",it->first.c_str());
			printf("...\n");
			it=children.end();
			for (int i=0; i<5; i++) it--;
			for (int i=0; i<5; i++,it++)printf("%s\n",it->first.c_str());
		}
	}
	void tree();
};
TREE的处理

后代节点一旦大于10,就要进行前序和后序的便利,并且观察数据范围我们会知道,如果每一次查询都进行遍历的话,绝对会超时。
因此我们应该做到缓存,也就是懒更新,当节点数远小于TREE操作数量,对于目录相同期间问过的相同问题,理应只有一次计算过程。

struct Directory
{
	/*其他*/
	vector<string>* tenDescendants;//保存当前节点的“十个后代”
	bool updated;//记录当前节点的子树有无变动,无变动则其“十个后代”无需更新
public:
	void tree(){
        if(subtreeSize==1) printf("EMPTY\n");
        else if(subtreeSize<=10){
            if(this->updated){
                tenDescendants->clear();
                treeAll(tenDescendants);
                this->updated=false;
            }
            for (int i=0; i<subtreeSize; i++) printf("%s\n",tenDescendants->at(i).c_str());
        }
        else {
            if(this->updated){
                tenDescendants->clear();
                treeFirstSome(5,tenDescendants);
                treeLastSome(5,tenDescendants);
                this->updated=false;
            }
            for (int i=0; i<5; i++) printf("%s\n",tenDescendants->at(i).c_str());
            printf("...\n");
            for (int i=9; i>=5; i--) printf("%s\n",tenDescendants->at(i).c_str());
        }
    }

private:
    void treeAll(vector<string>* bar) {//全部后代加入桶
        //更新整个桶
        bar->push_back(name);
        for (auto &entry: children) entry.second->treeAll(bar);
    }
    void treeFirstSome(int num,vector<string>* bar) {//前序遍历并加入首要的num个后代
        bar->push_back(name);
        if(--num==0) return;
        int n=children.size();
        auto it=children.begin();
        while(n--){
            int sts=it->second->subtreeSize;
            if(sts>=num){
                it->second->treeFirstSome(num,bar);
                return;
            }
            else {
                it->second->treeFirstSome(sts,bar);
                num-=sts;
            }
            it++;
        }
    }
    void treeLastSome(int num,vector<string>* bar) {//后序遍历并加入首要的num个后代
        int n=children.size();
        auto it=children.end();
        while(n--){
            it--;
            int sts=it->second->subtreeSize;
            if(sts>=num){
                it->second->treeLastSome(num,bar);
                return;
            }
            else {
                it->second->treeLastSome(sts,bar);
                num-=sts;
            }
        }
        bar->push_back(name);
    }
}

所有情况都处理完毕,最终完整代码如下:

完整代码

//#pragma GCC optimize(2)
//#pragma G++ optimize(2)
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <algorithm>
#include <queue>
#include <vector>
#include <map>
#include <stack>
using namespace std;

char tmps[200];
struct Directory
{
    string name;//当前目录的名字
    map<string ,Directory*> children;//用指针为了避免复制构造造成的内存浪费
    Directory* parent;//便于"CD.."要返回上级目录
    int subtreeSize;//便于“SZ”要输出子树大小
    vector<string>* tenDescendants;//保存当前节点的“十个后代”
    bool updated;//记录当前节点的子树有无变动,无变动则其“十个后代”无需更新
    Directory(string _name,Directory* _parent){
        name=_name;
        parent=_parent;
        subtreeSize=1;
        updated=false;
        children.clear();
        tenDescendants=new vector<string>;
    }
public:
    Directory* getChild(const string &_name){//取得子目录并返回,不存在就返回空指针
        auto it =children.find(_name);
        if(it==children.end()) return nullptr;
        return it->second;
    }
    Directory* mkdir(const string &_name){//创建子目录并返回,创建失败返回空指针
        if(children.find(_name) != children.end()) return nullptr;
        Directory* ch=new Directory(_name,this);
        children[_name]=ch;
        maintain(+1);
        return ch;
    }
    Directory* rm(const string &_name){//删除子目录并返回,删除失败则返回空指针
        auto it=children.find(_name);
        if(it==children.end()) return nullptr;
        maintain(-1*(it->second->subtreeSize));
        children.erase(it);
        return it->second;
    }
    Directory* cd(const string &_name){
        if(_name=="..")
            return this->parent;
        return getChild(_name);
    }
    bool addChild(Directory* ch){//加入子目录并返回成功与否
        if(children.find(ch->name)!=children.end()) return false;
        children[ch->name]=ch;
        maintain(ch->subtreeSize);
        return true;
    }
    void maintain(int delta){//向上维护子树的大小,便于实现"SZ"
        updated=true;
        subtreeSize+=delta;
        if(parent!=nullptr) parent->maintain(delta);
    }
    void sz(){
        printf("%d\n",this->subtreeSize);
    }
    void ls(){
        int sz=children.size();
        if(sz==0) printf("EMPTY\n");
        else if(sz<=10){
            for (auto &entry : children)
                printf("%s\n",entry.first.c_str());
        }
        else {
            auto it=children.begin();
            for (int i=0; i<5; i++,it++) printf("%s\n",it->first.c_str());
            printf("...\n");
            it=children.end();
            for (int i=0; i<5; i++) it--;
            for (int i=0; i<5; i++,it++) printf("%s\n",it->first.c_str());
        }
    }
    void tree(){
        if(subtreeSize==1) printf("EMPTY\n");
        else if(subtreeSize<=10){
            if(this->updated){
                tenDescendants->clear();
                treeAll(tenDescendants);
                this->updated=false;
            }
            for (int i=0; i<subtreeSize; i++) printf("%s\n",tenDescendants->at(i).c_str());
        }
        else {
            if(this->updated){
                tenDescendants->clear();
                treeFirstSome(5,tenDescendants);
                treeLastSome(5,tenDescendants);
                this->updated=false;
            }
            for (int i=0; i<5; i++) printf("%s\n",tenDescendants->at(i).c_str());
            printf("...\n");
            for (int i=9; i>=5; i--) printf("%s\n",tenDescendants->at(i).c_str());
        }
    }

private:
    void treeAll(vector<string>* bar) {//全部后代加入桶
        //更新整个桶
        bar->push_back(name);
        for (auto &entry: children) entry.second->treeAll(bar);
    }
    void treeFirstSome(int num,vector<string>* bar) {//前序遍历并加入首要的num个后代
        bar->push_back(name);
        if(--num==0) return;
        int n=children.size();
        auto it=children.begin();
        while(n--){
            int sts=it->second->subtreeSize;
            if(sts>=num){
                it->second->treeFirstSome(num,bar);
                return;
            }
            else {
                it->second->treeFirstSome(sts,bar);
                num-=sts;
            }
            it++;
        }
    }
    void treeLastSome(int num,vector<string>* bar) {//后序遍历并加入首要的num个后代
        int n=children.size();
        auto it=children.end();
        while(n--){
            it--;
            int sts=it->second->subtreeSize;
            if(sts>=num){
                it->second->treeLastSome(num,bar);
                return;
            }
            else {
                it->second->treeLastSome(sts,bar);
                num-=sts;
            }
        }
        bar->push_back(name);
    }
};
struct Command
{
    const string CMDNAMES[7]={"MKDIR","RM","CD","SZ","LS","TREE","UNDO"};
    int type;//命令的类型
    string arg;//命令的参数
    Directory* tmpDir;//记录刚刚操作设计的目录节点
    Command(const string &s){//构造函数
        tmpDir=nullptr;
        for (int i=0; i<7; i++){
            if(CMDNAMES[i]==s){
                type=i;
                if(i<3){//前三个都有参数
                    scanf("%s",tmps);
                    arg=tmps;
                    return;
                }
            }
        }
    }
};
void solve()
{
    int n=0;scanf("%d",&n);
    Directory* now=new Directory("root",nullptr);
    vector<Command*> cmdList;//新增加的数组,用来存成功执行的命令以便于"UNDO"
    cmdList.clear();
    while(n--){
        scanf("%s",tmps);
        Command* cmd=new Command(tmps);
        switch(cmd->type){
            case 0: case 1:{//MKDIR,RM
                cmd->tmpDir=cmd->type==0 ? now->mkdir(cmd->arg) : now->rm(cmd->arg);
                if(cmd->tmpDir==nullptr) printf("ERR\n");
                else {
                    printf("OK\n");
                    cmdList.push_back(cmd);
                }
                break;
            }
            case 2:{
                Directory* ch=now->cd(cmd->arg);
                if(ch==nullptr) printf("ERR\n");
                else {
                    printf("OK\n");
                    cmd->tmpDir=now;
                    now=ch;
                    cmdList.push_back(cmd);
                }
                break;
            }
            case 3: now->sz(); break;
            case 4: now->ls(); break;
            case 5: now->tree(); break;
            case 6:{
                bool success=false;//用来记录UNDO是否执行成功
                while(!success && !cmdList.empty()){
                    cmd=cmdList.back(); cmdList.pop_back();
                    switch(cmd->type){
                        case 0: success=now->rm(cmd->arg)!=nullptr; break;//undo MKDIR
                        case 1: success=now->addChild(cmd->tmpDir); break;//undo RM
                        case 2: now=cmd->tmpDir; success=true; break;//undo CD
                    }
                }
                printf(success ? "OK\n" : "ERR\n");
            }
        }
//        for (auto it:cmdList)
//            cout<<'*'<<it->type<<' '<<it->arg<<endl;
    }
}
int main()
{
    int T; scanf("%d",&T);//测试有T组数据
    for (int i=1; i<=T; i++) {
        solve();
        if(i!=T) printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值