题目1
输入int n, m;为矩形区域大小
小红从(0,0)出发,向下行走,每走过的格子由白变红,碰到障碍就左转
无路可走时停下,如果下两步会在地图里形成一个2*2的红***域则也会停下
输出最终的地图
例子
输入 5 5 输出 RWRWR RWRWR RWRWR RWWWR RRRRR
#include "iostream" #include "vector" using namespace std; int main() { int n, m; // scanf("%d %d", &n, &m); n = 5, m = 5; vector<vector<char>> vmap(n, vector<char>(m, 'W')); vector<vector<int>> dir = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; int i = 0, j = 0, did = 0; while (vmap[i][j] == 'W') { vmap[i][j] = 'R'; //不转弯的话,左边如果是 W就变为 N if (i + dir[did][0] >= n || j + dir[did][1] >= m || i + dir[did][0] < 0 || j + dir[did][1] < 0 || vmap[i + dir[did][0]][j + dir[did][1]] == 'N') { did = (did + 1) % 4; //转弯 } else { int li = i + dir[(did + 1) % 4][0], lj = j + dir[(did + 1) % 4][1]; if (vmap[li][lj] == 'W') vmap[li][lj] = 'N'; } //前进 i += dir[did][0]; j += dir[did][1]; } for (auto &vec : vmap) { for (char c : vec) { if (c == 'N') cout << 'W'; else cout << c; } cout << endl; } }
过了97,估计是没有考虑单行单列。。。
题目2
输入n节点个数
余下一行为搜索二叉树插入顺序
定义枝长度为 某节点 的一直向左的深度 或 一直向右的深度
输出最长枝长度以及最长枝数量
输入 6 5 2 6 3 1 4 输出 3 2
____5 / \ 2 6 / \ 1 3 \ 4 5->2->1, 2->3->4,两个最长枝长度为3
#include "iostream" #include "vector" using namespace std; struct TreeNode { int val; int ll; int lr; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; TreeNode *insert_tree(TreeNode *root, TreeNode *cur) { if (root == nullptr) { root = cur; root->ll = 1; root->lr = 1; return root; } TreeNode *tmp; tmp = root; if (cur->val < tmp->val) { if (tmp->left == nullptr) { tmp->left = cur; cur->ll = tmp->ll + 1; cur->lr = 1; } else { tmp->left = insert_tree(tmp->left, cur); } } else { if (tmp->right == nullptr) { tmp->right = cur; cur->ll = 1; cur->lr = tmp->lr + 1; } else { tmp->right = insert_tree(tmp->right, cur); } } return root; } int main() { int rst = 0, num = 0; TreeNode *root; root = nullptr; int n; scanf("%d", &n); while (n--) { int val; scanf("%d", &val); // infile >> val; //插入 TreeNode *cur = new TreeNode(val); root = insert_tree(root, cur); //更新末端节点左右值 if (cur->ll == rst) num++; if (cur->lr == rst) num++; if (cur->ll > rst || cur->lr > rst) { rst = max(cur->ll, cur->lr); num = 1; } } cout << rst << ' ' << num << endl; }
当时没过。。细节差好多
全部评论
(0) 回帖