专栏文章

题解:UVA587 There's treasure everywhere!

UVA587题解参与者 1已保存评论 0

文章操作

快速查看文章及其快照的属性,并进行相关操作。

当前评论
0 条
当前快照
1 份
快照标识符
@miox2sy7
此快照首次捕获于
2025/12/03 02:33
3 个月前
此快照最后确认于
2025/12/03 02:33
3 个月前
查看原文
一道思路完全不难的题目,只是写法对于 C++ 来说还是略显复杂了。
思路很简单,先处理每一个方向的单位向量的坐标,然后将这些坐标数乘后相加即可,没有什么思维难度的。
这里提供代码。特别的,由于本题使用 Python 可以大幅减少代码量同时常数也没有很大,所以也提供 Python 的代码。
CPP
#include <bits/stdc++.h>
using namespace std;

int main()
{
    constexpr double sqrt2_div2 = sqrt(2.0) / 2.0;
    map<string, pair<double, double>>
        dir_map={
        {"N",  {0.0, 1.0}},
        {"NE", {sqrt2_div2, sqrt2_div2}},
        {"E",  {1.0, 0.0}},
        {"SE", {sqrt2_div2, -sqrt2_div2}},
        {"S",  {0.0, -1.0}},
        {"SW", {-sqrt2_div2, -sqrt2_div2}},
        {"W",  {-1.0, 0.0}},
        {"NW", {-sqrt2_div2, sqrt2_div2}}
    };

    string line;
    int case_num = 1;

    while (getline(cin, line))
    {
        if (line == "END") break;
        if (!line.empty() && line.back() == '.')
            line.pop_back();
        vector<string> commands;
        stringstream ss(line);
        string token;
        // 这里有一个小 trick,应该可以看出来
        while (getline(ss, token, ','))
            commands.push_back(token);

        double x = 0.0, y = 0.0;
        for (string& cmd : commands)
        {
            size_t i = 0;
            while (i < cmd.length() && isdigit(cmd[i]))
                i++;
            if (i == 0) continue;
            
            int steps = stoi(cmd.substr(0, i));
            string dir_str = cmd.substr(i);
            if (dir_map.find(dir_str) != dir_map.end())
            {
                double dx = dir_map[dir_str].first * steps;
                double dy = dir_map[dir_str].second * steps;
                x += dx;
                y += dy;
            }
        }
        double distance = sqrt(x*x + y*y);
        cout << "Map #" << case_num << '\n' << fixed << setprecision(3) << "The treasure is located at (" << x << "," << y << ").\nThe distance to the treasure is " << distance << ".\n\n";
        
        ++case_num;
    }

    return 0;
}
PY
import sys
cnt = 0
sqrt2 = 2 ** 0.5
opt = {"N":(0,1), "S":(0,-1), "E":(1,0), "W":(-1,0), "NW":(-sqrt2/2,sqrt2/2), "NE":(sqrt2/2,sqrt2/2), "SW":(-sqrt2/2,-sqrt2/2), "SE":(sqrt2/2,-sqrt2/2)}
while True:
    seq = sys.stdin.readline().strip().strip('.').split(',')
    X , Y = 0 , 0
    if seq == ['END']:
        break
    cnt += 1
    print("Map", "#" + str(cnt))
    for _ in seq:
        if "A" <= _[-2] <= "Z":
            wy = _[-2:]
            ln = int(_[:-2])
        else:
            wy = _[-1]
            ln = int(_[:-1])
        X += opt[wy][0]*ln
        Y += opt[wy][1]*ln
    print("The treasure is located at ({:.3f},{:.3f}).\nThe distance to the treasure is {:.3f}.\n".format(X, Y, (X ** 2 + Y ** 2) ** 0.5))
对了,什么时候能用 Python 了,或者能够支持 C++ 的 std::format 之类的好东西了,记得来考个古,现在只能用一般的 cout 的代码写成了什么样子……

评论

0 条评论,欢迎与作者交流。

正在加载评论...