1 条题解
-
0
题意
本题的目标是编写一个简单的电子表格应用程序。输入文件会先给出需要处理的电子表格数量,接着每个电子表格会先给出其列数和行数,随后逐行给出每个单元格的内容。单元格内容可以是整数数值,也可以是仅支持求和的公式(以开头,后面跟着一个或多个单元格名称,用分隔)。程序需要计算所有公式的值,最终输出结果表格,其中所有公式都要替换为计算后的值。
解题思路
数据读取:先读取电子表格的数量,再针对每个电子表格,读取其列数和行数,接着读取每个单元格的内容并存储起来。
单元格内容解析:对每个单元格的内容进行解析,若为数值则直接存储;若为公式,则记录下该公式所引用的单元格。
公式计算:借助递归的方式计算每个公式的值,直至所有公式都被计算完毕。
结果输出:输出计算完成后的表格,此时所有公式都已替换为计算值。
#include <iostream> #include <vector> #include <string> #include <sstream> #include <unordered_map> using namespace std; // 转换列名到列索引 int columnToIndex(const string& col) { int index = 0; for (char c : col) { index = index * 26 + (c - 'A' + 1); } return index - 1; } // 解析单元格名称 pair<int, int> parseCell(const string& cell) { string col; int row; for (char c : cell) { if (isalpha(c)) { col += c; } else { row = stoi(cell.substr(col.length())); break; } } return {columnToIndex(col), row - 1}; } // 计算公式的值 int calculateFormula(const vector<vector<string>>& sheet, unordered_map<string, int>& memo, const string& formula) { if (memo.find(formula) != memo.end()) { return memo[formula]; } int sum = 0; istringstream iss(formula.substr(1)); string cell; while (getline(iss, cell, '+')) { auto [col, row] = parseCell(cell); string value = sheet[row][col]; if (value[0] == '=') { sum += calculateFormula(sheet, memo, value); } else { sum += stoi(value); } } memo[formula] = sum; return sum; } // 处理电子表格 vector<vector<int>> processSpreadsheet(const vector<vector<string>>& sheet) { int rows = sheet.size(); int cols = sheet[0].size(); vector<vector<int>> result(rows, vector<int>(cols)); unordered_map<string, int> memo; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string cell = sheet[i][j]; if (cell[0] == '=') { result[i][j] = calculateFormula(sheet, memo, cell); } else { result[i][j] = stoi(cell); } } } return result; } int main() { int numSpreadsheets; cin >> numSpreadsheets; for (int s = 0; s < numSpreadsheets; ++s) { int cols, rows; cin >> cols >> rows; vector<vector<string>> sheet(rows, vector<string>(cols)); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cin >> sheet[i][j]; } } auto result = processSpreadsheet(sheet); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (j > 0) { cout << " "; } cout << result[i][j]; } cout << endl; } } return 0; }
- 1
信息
- ID
- 421
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 7
- 已通过
- 1
- 上传者