1 条题解
-
0
题目分析
题目要求我们根据给定的传统藏宝图,计算宝藏的精确位置和从起点到宝藏的直线距离。藏宝图由一系列方向和步数组成,每个方向代表八个基本罗盘方向之一。我们需要将这些步数和方向转换为坐标变化,最终计算宝藏的坐标和直线距离。
解题思路
- 解析输入:每个藏宝图由一个字符串表示,包含多个逗号分隔的步数和方向组合,以句号结束。例如,"3N,1E,1N,3E,2S,1W."。
- 方向处理:将每个方向转换为对应的坐标变化。例如:
- N (北) → y += step
- NE (东北) → x += step / √2, y += step / √2
- E (东) → x += step
- SE (东南) → x += step / √2, y -= step / √2
- S (南) → y -= step
- SW (西南) → x -= step / √2, y -= step / √2
- W (西) → x -= step
- NW (西北) → x -= step / √2, y += step / √2
- 坐标计算:遍历每个步数和方向,更新当前坐标 (x, y)。
- 距离计算:使用欧几里得距离公式计算从原点 (0, 0) 到 (x, y) 的距离,即
sqrt(x^2 + y^2)
。 - 输出结果:按照指定格式输出坐标和距离,保留三位小数。
正确代码
#include <iostream> #include <string> #include <vector> #include <cmath> #include <iomanip> #include <sstream> using namespace std; struct Point { double x, y; Point() : x(0), y(0) {} void move(int steps, const string& dir) { if (dir == "N") y += steps; else if (dir == "NE") { x += steps/sqrt(2); y += steps/sqrt(2); } else if (dir == "E") x += steps; else if (dir == "SE") { x += steps/sqrt(2); y -= steps/sqrt(2); } else if (dir == "S") y -= steps; else if (dir == "SW") { x -= steps/sqrt(2); y -= steps/sqrt(2); } else if (dir == "W") x -= steps; else if (dir == "NW") { x -= steps/sqrt(2); y += steps/sqrt(2); } } }; vector<string> split_commands(const string& s) { vector<string> commands; size_t start = 0; size_t end = s.find(','); while (end != string::npos) { commands.push_back(s.substr(start, end - start)); start = end + 1; end = s.find(',', start); } commands.push_back(s.substr(start, s.size() - start - 1)); // 去掉最后的点 return commands; } void process_map(const string& map_desc, int map_num) { Point treasure; vector<string> commands = split_commands(map_desc); for (const string& cmd : commands) { size_t dir_pos = 0; while (dir_pos < cmd.size() && isdigit(cmd[dir_pos])) { dir_pos++; } int steps = stoi(cmd.substr(0, dir_pos)); string dir = cmd.substr(dir_pos); treasure.move(steps, dir); } double distance = sqrt(treasure.x * treasure.x + treasure.y * treasure.y); cout << "Map #" << map_num << endl; cout << fixed << setprecision(3); cout << "The treasure is located at (" << treasure.x << "," << treasure.y << ")." << endl; cout << "The distance to the treasure is " << distance << "." << endl; cout << endl; } int main() { string line; int map_num = 1; while (getline(cin, line)) { if (line == "END") break; process_map(line, map_num); map_num++; } return 0; }
- 1
信息
- ID
- 474
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 10
- 已通过
- 1
- 上传者