Untitled
unknown
plain_text
a year ago
2.1 kB
3
Indexable
Never
#include <iostream> #include <vector> #include <stack> #include <algorithm> #include <functional> using namespace std; struct Item { char type; // 'd', 'e', 'f' int size; // 有效当type='f' vector<Item> children; int totalSize() const { if(type == 'f') return size; int sum = 0; for(const auto& child : children) { sum += child.totalSize(); } return sum; } }; // 自定义的比较函数,用于排序 bool compareItems(const Item& a, const Item& b) { return a.totalSize() < b.totalSize(); } void printItems(const Item& item) { cout << item.type << " "; if(item.type == 'f') { cout << item.size << " "; } else if(item.type == 'd') { for(const auto& child : item.children) { printItems(child); } cout << "e "; } } int main() { string inputType; int size; stack<Item*> directoryStack; Item root; root.type = 'd'; directoryStack.push(&root); while(cin >> inputType) { if(inputType == "d") { Item newDirectory; newDirectory.type = 'd'; directoryStack.top()->children.push_back(newDirectory); directoryStack.push(&directoryStack.top()->children.back()); } else if(inputType == "e") { directoryStack.pop(); } else if(inputType == "f") { cin >> size; Item file; file.type = 'f'; file.size = size; directoryStack.top()->children.push_back(file); } } // 对每一个目录进行递归排序 function<void(Item&)> sortItems = [&](Item& dir) { for(auto& child : dir.children) { if(child.type == 'd') sortItems(child); } sort(dir.children.begin(), dir.children.end(), compareItems); }; sortItems(root); for(const auto& item : root.children) { printItems(item); } return 0; }