6 条题解
-
-11
#include <iostream> #include <vector> #include <string> #include <sstream> #include <utility> // 用于pair using namespace std; int sumOfLeftLeaves() { // 读取总节点数 string line; getline(cin, line); int n = atoi(line.c_str()); // C++03没有stoi,使用atoi if (n == 0) { return 0; } // 存储每个节点的左右子节点信息 // C++03中vector内的空格不能省略,且需显式指定模板参数 vector<pair<string, string> > children(n + 1); for (int i = 1; i <= n; ++i) { getline(cin, line); istringstream iss(line); string left, right; iss >> left >> right; // C++03需要使用make_pair创建pair对象 children[i] = make_pair(left, right); } // 计算左叶子之和 int total = 0; // 遍历所有可能的父节点 for (int parent = 1; parent <= n; ++parent) { string leftChild = children[parent].first; // 检查是否有左子节点 if (leftChild != "*") { int leftChildNum = atoi(leftChild.c_str()); // 检查左子节点是否为叶子节点 if (children[leftChildNum].first == "*" && children[leftChildNum].second == "*") { total += leftChildNum; } } } return total; } int main() { cout << sumOfLeftLeaves() << endl; return 0; } ```
信息
- ID
- 2819
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 3
- 标签
- 递交数
- 70
- 已通过
- 19
- 上传者