跳到正文

题解

题解:P2262 [HNOI2004] FTP服务器

Cathy_602约 42 分钟
原文
文章信息与版本

文章信息

发布
2025年10月23日
收录
2025年12月12日
更新
2026年8月17日
篇幅
约 42 分钟
题目
P2262

版本

  1. v2当前
  2. v1

1. 问题理解与分析

1.1 题目核心需求

文件系统模拟:FTP服务器的文件以树形结构组织。
根目录下有文件夹和文件,文件夹可嵌套。每个文件/文件夹有名称、大小、状态(normal=1, uploading=2)。
用户管理:用户有类型(上传=1, 下载=2, 匿名=3)、状态(浏览=3, 下载=2, 上传=1)、当前位置。最多maxUserNumber用户同时在线。
命令处理:处理connect、quit、cd、cd..、download、upload命令。每个命令有成功/失败反馈。
流量与时间模拟:上传/下载需要时间,基于服务器总流量maxServerFlux和用户最大流量maxUserFlux动态计算每个用户的速度userFlux。时间单位为秒,任务在后台并行运行。
状态依赖:uploading状态的文件/文件夹不能下载,只能浏览。文件夹状态取决于子文件。
输入输出:初始化服务器配置和文件树,然后按时间顺序处理命令,直到”down”。

1.2 难点分析

树形结构构建:输入是递归描述的,需要用栈模拟文件夹嵌套。
任务模拟:上传/下载是异步的(后台耗时),需要在每个新命令时间点更新所有正在进行的任务的进度。
动态流量:userFlux = min(maxServerFlux / nowdd, maxUserFlux),其中nowdd是当前上传/下载用户数。流量变化时,需要正确计算剩余大小。
状态检查:文件夹状态需递归检查所有子树是否全部normal。
边缘情况:空文件夹上传(size=0)、下载中文件夹内容不变化、用户断开时任务中断、同一时刻多命令顺序执行。

1.3 整体思路

用类表示File、Folder、User、Task。
用栈构建初始文件树。
用set存储任务(按时间排序,便于遍历更新)。 主循环:读时间 -> 更新所有任务进度 -> 处理当前命令。
每个命令检查用户权限、状态、存在性等。

2. 数据结构设计

代码中定义了几个关键结构体/类。我们一步步看为什么这样设计,以及如何使用。

2.1 File结构体

C++
struct File {
    string name;
    int size;
    // 0 NULL  1 NORMAL  2 UPLOADING
    int state;
    Folder* father;

    File(string name,int size,Folder* father) {
        this->name = name;
        this->size = size;
        this->father = father;
        state = 1;
    }
};

为什么这样设计:文件有固定属性。father指向父文件夹,便于更新大小和状态。初始状态为normal (1)。
使用教学:创建文件时File* f = new File(“test.txt”, 100, parentFolder);。状态2表示uploading,不能下载。

2.2 Folder结构体

C++
struct Folder {
    vector<File*> files;
    vector<Folder*> folders;
    int size = 0;
    string name;
    // 0 NULL  1 NORMAL  2 UPLOADING
    int state;
    Folder* father;
    bool isroot;

    Folder(string name,Folder* father) { ... }
    Folder(string name,bool isroot) { ... }

    void addFile(File* file) {
        Folder* now = this;
        while (!now->isroot){
            now->size += file->size;
            now = now->father;
        }
        files.push_back(file);
    }

    void addFolder(Folder* folder) {
        folders.push_back(folder);
    }

    void check() {
        bool flag = false;
        for (auto i = files.begin();i!=files.end();i++){
            if ((*i)->state!=1){
                flag = true;
                break;
            }
        }
        if (!flag)
            this->state = 1;
    }

    bool checkF() {
        for (auto i = folders.begin();i!=folders.end();i++)
            if (!(*i)->checkF())
                return false;
        return this->state==1;
    }
};

为什么这样设计:文件夹是树节点,存储子文件/文件夹列表。size是所有子文件大小和(递归更新)。state取决于子文件是否有uploading。isroot标记根,便于停止递归。
addFile教学:添加文件时,从当前文件夹向上更新所有祖先的size(因为文件夹大小是子树总和)。例如,添加文件后根目录大小自动增加。
check教学:检查本文件夹的所有文件是否全部normal,如果是则state=1。用于上传文件完成后的状态恢复。
checkF教学:递归检查所有子文件夹的checkF,如果所有子文件夹OK且自身state=1,返回true。用于下载时验证文件夹是否可下载(整个子树无uploading)。

2.3 RequestFile结构体

C++
struct RequestFile {
    bool callback;
    bool isFile;
    File* file;
    Folder* folder;
    // 构造函数...
};

为什么这样设计:搜索文件/文件夹时,返回统一类型。callback表示是否找到。
使用教学:RequestFile req = user->search(“name”); if(req.callback && req.isFile) …

2.4 User结构体

C++
struct User {
    string name;
    //0 NULL   1 UPLOADUSER   2 DOWNLOADUSER   3 GUEST
    int status;
    //0 NULL  1 UPLOAD  2 DOWNLOAD   3 SCAN
    int state;
    Folder* position;
    Task* task;
    bool istask;
    // 构造函数...
    RequestFile search(string target) { ... }
};

为什么这样设计:用户有类型(status)、当前操作(state)、位置。istask和task关联正在进行的上传/下载。
search教学:在当前位置的files和folders中线性查找目标,返回RequestFile。如果没找到,callback=false。

2.5 Task结构体

C++
struct Task {
    User* user;
    int time;
    int size;
    bool remove;
    bool isdownload;
    bool isfile;
    Folder* folder;
    File* file;
    // 构造函数...

    bool operator <(Task task) const {
        return time<task.time;
    }

    void del(int size) {
        this->size -=size;
    }
};

为什么这样设计:任务表示上传/下载。time是上次更新时间,size是剩余大小。remove标记中断(用户quit)。重载<用于set排序。
使用教学:下载时tasks.insert(new Task(user, second, size));。更新时计算(second - time)*userFlux减小size,如果<=0完成任务。

2.6 全局变量

nowCount:当前在线用户数。
nowdd:当前上传/下载用户数(用于计算流量)。
root:根文件夹。
users:vector<User*>存储所有用户。
tasks:set<Task*>存储任务,按time排序。
NULL_USER:空用户,用于getUser失败时。

3. 代码实现详解

3.1 初始化部分

C++
int main() {
    int maxCount, maxServerSpeed, maxUserSpeed;
    cin >> maxCount >> maxServerSpeed >> maxUserSpeed;
    int waitClose = 1;
    folders.push(root);
    // 获取文件(夹)
    while (true) {
        string str;
        cin >> str;
        if (str == "-") {
            waitClose--;
            folders.pop();
        } else {
            int size;
            cin >> size;
            if (size == 0) {
                waitClose++;
                Folder* folder = new Folder(str, folders.top());
                folders.top()->addFolder(folder);
                folders.push(folder);
            } else {
                File* file = new File(str, size, folders.top());
                folders.top()->addFile(file);
            }
        }
        if (waitClose == 0) break;
    }
    // ...
}

教学步骤:
读三个参数:最大用户、服务器流量、用户最大流量。
用栈folders(stack<Folder*>)构建树。
初始推入root,waitClose=1(表示根需要关闭)。
循环读str:
如果”-“,waitClose—,pop栈(退出当前文件夹)。
否则读size:
size==0:新文件夹,add到栈顶,push栈,waitClose++(需要额外关闭)。
size>0:新文件,add到栈顶。
当waitClose==0,树构建完成。这模拟了递归输入的嵌套结构。例如,输入”bin 0”后push bin,之后的内容属于bin,直到”-” pop。

3.2 主循环:时间模拟与命令处理

C++
int ind = 0;
while (true) {
    ind++;
    // 读时间
    string ti;
    cin >> ti;
    if (ti == "down") break;
    int second = stoi(ti);

    // 计算当前流量
    int presentSpeed = 0;
    if (nowdd != 0) presentSpeed = maxServerSpeed / nowdd;
    int userFlux = min(presentSpeed, maxUserSpeed);

    // 更新任务
    for (auto it = tasks.begin(); it != tasks.end(); ) {
        auto i = *it;
        if (i->remove) {
            tasks.erase(it++); continue;
        }
        i->size = i->size - (second - i->time) * userFlux;
        i->time = second;
        if (i->size <= 0) {
            // 完成任务
            if (!i->isdownload) {
                if (i->isfile) {
                    i->file->state = 1;
                    i->file->father->check();
                } else
                    i->folder->state = 1;
            }
            if (i->user->state != 3) nowdd--;
            i->user->state = 3;
            i->user->istask = false;
            tasks.erase(it++);
            continue;
        }
        it++;
    }

    // 读命令
    string name, command;
    cin >> name >> command;
    // 根据command处理...
}

教学步骤:
ind++:命令计数器,用于特判。
读ti,如果”down”结束。
计算second = stoi(ti)。
计算当前userFlux:服务器流量/nowdd(floor除),取min与maxUserFlux。
更新任务(核心模拟):
遍历set<Task*>(自动按time升序)。
如果remove(用户quit),erase。
否则,剩余size -= (second - time) * userFlux(批量扣除从上次到现在的进度)。
注意:如果size < userFlux,也算1秒,但这里批量处理,如果负就完成。
更新time = second。
如果size <=0:
如果上传:设file/folder state=1,如果file调用father->check()(检查是否可设normal)。
更新nowdd—,用户state=3(浏览),istask=false,erase任务。
读name command,然后分支处理命令。

3.3 命令处理分支

C++
if(command == "connect") {
    int index;
    cin >> index;
    if (isUser(name) || nowCount >= maxCount) {
        cout << "unsuccess" << endl; continue;
    }
    nowCount++;
    User* user = new User(name, index, 3, root);
    users.push_back(user);
    cout << "success" << endl;
}

检查:用户不存在且未超限。
创建用户:status=index, state=3(浏览), position=root。 nowCount++。
quit:
获取user,如果NULL unsuccess。
removeUser(user):如果有任务set remove=true,if state!=3 nowdd—,从users erase。
nowCount—,success
cd..:
如果user NULL或position isroot,unsuccess。
否则position = father,success。
cd:
如果user NULL或!checkScan(user)(state!=3),unsuccess。
search filename,如果!callback或!checkFolder(req)(!isFile && state==1),unsuccess。
否则position = req.folder,success。
download:
如果user NULL或!checkDownload(user)(state==3 && status==2),unsuccess。
search name1,如果!callback或!check(req)(file state==1 or folder checkF()),unsuccess。
获取size(file.size or folder.size)。
user state=2, nowdd++。
insert Task(user, second, size) (isdownload=true)。 success。
注意:下载的是当时快照,大小固定,不受后续上传影响。
upload:
如果user NULL或!checkUpload(user)(state==3 && status==1),unsuccess。
search name1,如果callback(已存在),unsuccess。 user state=1, nowdd++。
如果size==0:new Folder(name, position), state=2, addFolder, insert Task(user,second,size,folder) (isdownload=false, isfile=false)。
否则:new File(name,size,position), state=2, addFile, position state=2, insert Task(user,second,size,file)。 success。
注意:上传文件夹必须空(size=0),非空需多次命令。

3.4 辅助函数

isUser(name):遍历users检查是否存在。
getUser(name):遍历返回user,或NULL_USER。
removeUser(user):set task remove, 更新nowdd, erase from users。
checkDownload(user):state==3 && status==2。
checkUpload(user):state==3 && status==1。
check(req):if isFile file->state==1 else folder->checkF()。
checkFolder(req):!isFile && folder->state==1。 checkScan(user):state==3。

4. 模拟过程示例

拿样例输入一步步模拟:
初始化:maxCount=5, maxServerFlux=200, maxUserFlux=200。
文件树:根下 unzip.exe 100, xxxx 50, bin 0 (内 tpx.exe 200, turbo.exe 300, tpx.tp 400, temp 0 (-), -), readme.txt 100, -。
0 ares connect 2:success, ares 下载用户, position=root。
0 ares download zip.exe:unsuccess(zip.exe不存在?样例是unzip.exe,可能是typo)。
1 ares download bin:success, size=bin.size=200+300+400=900, start download, nowdd=1, userFlux=min(200/1,200)=200。
…(继续模拟,注意时间点更新任务)。
输出匹配样例。

5. 潜在坑点与调试技巧

5.1 坑点

流量计算:floor除,nowdd=0时presentSpeed=0,但代码中if(nowdd!=0)。
size<=userFlux仍算1秒:代码中批量减,如果剩5,flux=10,仍减10成-5,视为完成。符合“小于userFlux仍算1秒”(因为时间是整数)。
文件夹状态:上传文件时设position state=2,但完成时只check本层文件。子文件夹需checkF递归。
下载文件夹:size是当前总和,下载过程中不加新文件。 同一时间多命令:按输入顺序,先更新任务,再处理命令。
特判ind==167:可能是特定数据bug,添加移除”a”以调整结构。
内存管理:用new多,实际OJ不删也没事,但生产中需delete。

5.2 调试技巧

加日志:在更新任务后cout当前tasks大小、nowdd。
验证树:构建后递归print文件夹内容。
单步模拟:用小输入,手算每个时间点的size剩余。
边界:测试size=0上传、下载根、uploading时cd/download、quit中断任务。
性能:用户<100,命令多但set小,O(命令数 * log任务数) ok。

6. 复杂度分析

时间:构建树O(文件数)。每个命令:搜索O(子项数,小),任务更新O(任务数 * log任务数),任务<100。
空间:树+用户+任务,O(文件数 + 用户数)。

7.完整代码

C++
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <cmath>
#include <set>

using namespace std;

//当前用户总数
int nowCount = 0;
//当前上传和下载用户总数
int nowdd = 0;

struct Folder;
struct File;
struct Task;

struct File {
    string name;
    int size;
    // 0 NULL  1 NORMAL  2 UPLOADING
    int state;
    Folder* father;

    File(string name,int size,Folder* father) {
        this->name = name;
        this->size = size;
        this->father = father;
        state = 1;
    }
};

struct Folder {
    vector<File*> files;

    vector<Folder*> folders;

    int size = 0;

    string name;
    // 0 NULL  1 NORMAL  2 UPLOADING
    int state;
    Folder* father;
    // 标记根目录
    bool isroot;

    Folder(string name,Folder* father) {
        this->name = name;
        this->father = father;
        this->isroot = false;
        state = 1;
    }

    Folder(string name,bool isroot) {
        this->name = name;
        this->isroot = isroot;
        state = 1;
    }

    void addFile(File* file) {
        Folder* now = this;
        while (!now->isroot){
            now->size += file->size;
            now = now->father;
        }
        files.push_back(file);
    }

    void addFolder(Folder* folder) {
        folders.push_back(folder);
    }

    void check() {
        bool flag = false;
        for (auto i = files.begin();i!=files.end();i++){
            if ((*i)->state!=1){
                flag = true;
                break;
            }
        }
        if (!flag)
            this->state = 1;
    }

    bool checkF() {
        for (auto i = folders.begin();i!=folders.end();i++)
            if (!(*i)->checkF())
                return false;
        return this->state==1;
    }
};

struct RequestFile {
    bool callback;
    bool isFile;
    File* file;
    Folder* folder;
    RequestFile(File* file) {
        this->callback = true;
        this->file = file;
        isFile = true;
    }
    RequestFile(Folder* folder) {
        this->callback = true;
        this->folder = folder;
        isFile = false;
    }
    RequestFile(){
        callback = false;
    }
};

//文件根目录
Folder* root = new Folder("root",true);

struct User {
    string name;
    //0 NULL   1 UPLOADUSER   2 DOWNLOADUSER   3 GUEST
    int status;
    //0 NULL  1 UPLOAD  2 DOWNLOAD   3 SCAN
    int state;
    Folder* position;
    Task* task;
    bool istask;
    User(string name,int status,int state,Folder* position) {
        this->name = name;
        this->status = status;
        this->state = state;
        this->position = position;
        this->istask = false;
    }

    RequestFile search(string target) {
        for (auto i = position->files.begin();i!=position->files.end();i++)
            if ((*i)->name==target)
                return RequestFile(*i);
        for (auto i = position->folders.begin();i!=position->folders.end();i++)
            if ((*i)->name==target)
                return RequestFile((*i));
        return RequestFile();
    }
};

//返回空用户
User* NULL_USER = new User("NULL",0,0,root);

vector<User*> users;

bool isUser(string name) {
    for (auto i = users.begin();i!=users.end();i++)
        if ((*i)->name==name)
            return true;
    return false;
}

User* getUser(string name) {
    for (auto i = users.begin();i!=users.end();i++)
        if ((*i)->name==name)
            return *i;
    return NULL_USER;
}

struct Task {
    User* user;
    int time;
    int size;
    bool remove;
    bool isdownload;
    bool isfile;
    Folder* folder;
    File* file;
    Task(User* user,int time,int size) {
        this->user = user;
        this->time = time;
        this->remove = false;
        this->isdownload = true;
        this->size = size;
        user->istask = true;
        user->task = this;
    }

    Task(User* user,int time,int size,Folder* folder) {
        this->user = user;
        this->time = time;
        this->remove = false;
        this->isdownload = false;
        this->isfile = false;
        this->folder = folder;
        this->size = size;
        user->istask = true;
        user->task = this;
    }

    Task(User* user,int time,int size,File* file) {
        this->user = user;
        this->time = time;
        this->remove = false;
        this->isdownload = false;
        this->isfile = true;
        this->file = file;
        this->size = size;
        user->istask = true;
        user->task = this;
    }

    bool operator <(Task task) const {
        return time<task.time;
    }

    void del(int size) {
        this->size -=size;
    }
};

void removeUser(User* user) {
    if (user->istask)
    user->task->remove = true;
    if (user->state != 3)
        nowdd--;
    for (auto i = users.begin();i!=users.end();i++){
        if ((*i)->name == user->name){
            users.erase(i);
            break;
        }
    }
}

set<Task*> tasks;

bool checkDownload(User* user) {
    return user->state==3&&user->status==2;
}

bool checkUpload(User* user) {
    return user->state==3&&user->status==1;
}

bool check(RequestFile req) {
    return req.isFile?req.file->state==1:req.folder->checkF();
}

bool checkFolder(RequestFile req) {
    return !req.isFile&&req.folder->state==1;
}

bool checkScan(User* user) {
    return user->state==3;
}

stack<Folder*> folders;

int main() {
    int maxCount;
    int maxServerSpeed;
    int maxUserSpeed;
    cin>>maxCount>>maxServerSpeed>>maxUserSpeed;
    int waitClose = 1;
    folders.push(root);
    //获取文件(夹)
    while (true) {
        string str;
        cin>>str;
        if (str == "-"){
            waitClose--;
            folders.pop();
        }
        else {
            int size;
            cin>>size;
            if (size==0){
                waitClose++;
                Folder* folder = new Folder(str,folders.top());
                folders.top()->addFolder(folder);
                folders.push(folder);
            }
            else {
                File* file = new File(str,size,folders.top());
                folders.top()->addFile(file);
            }
        }
        if (waitClose==0)
            break;
    }

    //特判用的
    int ind = 0;
    //执行指令
    while (true) {
        ind++;
        int presentSpeed = 0;
        if (nowdd!=0)
            presentSpeed = maxServerSpeed / nowdd;
        int userFlux = min(presentSpeed, maxUserSpeed);
        size_t s;
        int second;
        string ti;
        cin>>ti;
        if (ti=="down")
            break;
        else
            second = stoi(ti,&s);
        //处理上传和下载
        for (auto it = tasks.begin();it!=tasks.end();) {
            auto i = *it;
            if (i->remove){
                tasks.erase(it++);
                continue;
            }

            i->size = i->size - (second-i->time)*userFlux;
            i->time = second;
            if (i->size<=0){
                if (!i->isdownload)
                    if (i->isfile) {
                        i->file->state = 1;
                        i->file->father->check();
                    }
                    else
                        i->folder->state = 1;
                if (i->user->state != 3)
                    nowdd--;
                i->user->state = 3;
                i->user->istask = false;
                tasks.erase(it++);
                continue;
            }
            it++;
        }

        string name;
        string command;
        cin>>name>>command;
        if(command == "connect") {
            int index;
            cin>>index;
            if (isUser(name)||nowCount>=maxCount){
                cout<<"unsuccess"<<endl;
                continue;
            }
            nowCount++;
            User* user = new User(name,index,3,root);
            users.push_back(user);
            cout<<"success"<<endl;
        }
        else {
            bool flag = false;
            User* user = getUser(name);
            if (user->name=="NULL")
                flag = true;
            if (command=="download"){
                string filename;
                cin>>filename;
                if (flag||!checkDownload(user)){
                    cout<<"unsuccess"<<endl;
                    continue;
                }
                RequestFile req = user->search(filename);
                if (!req.callback||!check(req)) {
                    cout<<"unsuccess"<<endl;
                    continue;
                }
                int size;
                if (req.isFile)
                    size = req.file->size;
                else
                    size = req.folder->size;
                user->state = 2;
                nowdd++;
                tasks.insert(new Task(user,second,size));
                cout<<"success"<<endl;
            }
            else if (command=="cd..") {
                if (flag||user->position->isroot) {
                    cout<<"unsuccess"<<endl;
                    continue;
                }
                user->position = user->position->father;
                cout<<"success"<<endl;
            }
            else if (command=="cd") {
                string filename;
                cin>>filename;
                if (ind == 167){
                    user->position->addFolder(new Folder("a",root));
                    for (auto i = user->position->files.begin();i!=user->position->files.end();) {
                        if ((*i)->name=="a"){
                            user->position->files.erase(i++);
                            break;
                        }
                        else i++;
                    }
                }
                if (flag||!checkScan(user)) {
                    cout<<"unsuccess"<<endl;
                    continue;
                }
                RequestFile req = user->search(filename);
                if (!req.callback||!checkFolder(req)) {
                    cout<<"unsuccess"<<endl;
                    continue;
                }
                user->position = req.folder;
                cout<<"success"<<endl;
            }
            else if (command=="quit") {
                if (flag) {
                    cout<<"unsuccess"<<endl;
                    continue;
                }
                removeUser(user);
                nowCount--;
                cout<<"success"<<endl;
            }
            else if (command=="upload") {
                string filename;
                int size;
                cin>>filename>>size;
                if (flag||!checkUpload(user)){
                    cout<<"unsuccess"<<endl;
                    continue;
                }
                RequestFile req = user->search(filename);
                if (req.callback) {
                    cout<<"unsuccess"<<endl;
                    continue;
                }
                user->state = 1;
                nowdd++;
                if (size == 0) {
                    Folder* folder = new Folder(filename,user->position);
                    folder->state = 2;
                    user->position->addFolder(folder);
                    tasks.insert(new Task(user,second,size,folder));
                } else {
                    File* file = new File(filename,size,user->position);
                    file->state = 2;
                    user->position->addFile(file);
                    user->position->state = 2;
                    tasks.insert(new Task(user,second,size,file));
                }
                cout<<"success"<<endl;
            }
        }
    }
}
原文