Files
leetcode-master/problems/kamacoder/0160.二维平面上的折线段.md
programmercarl 574cef48b3 Update
2024-08-29 20:39:18 +08:00

2.4 KiB

二维平面上的折线段

题目链接:https://kamacoder.com/problempage.php?pid=1238

这个问题要求我们在一条折线段上,根据移动的固定距离 s 进行标记点的计算。

为了实现这一点,我们需要对折线段进行分段处理,并根据每段的长度来确定标记点的位置。

解题思路:

  1. 输入与初步处理:
    • 首先,读取所有点的坐标。
    • 计算每一段折线的长度,并逐段累积总长度。
  2. 确定标记点:
    • 从起点开始,每次沿着折线段前进 s 的距离,直到到达终点。
    • 对于每个标记点,根据当前段的起点和终点,计算出该点的精确坐标。
  3. 输出所有标记点的坐标,格式为 x, y。

#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>

using namespace std;

// 定义一个点的结构体
struct Point {
    double x, y;
};

// 计算两点之间的距离
double distance(const Point& a, const Point& b) {
    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}

int main() {
    int n;
    cin >> n;

    vector<Point> points(n);
    for (int i = 0; i < n; i++) {
        cin >> points[i].x >> points[i].y;
    }

    double s;
    cin >> s;

    double total_length = 0.0;
    vector<double> segment_lengths(n - 1);

    // 计算每段长度和总长度
    for (int i = 0; i < n - 1; i++) {
        segment_lengths[i] = distance(points[i], points[i + 1]);
        total_length += segment_lengths[i];
    }

    // 从起点开始标记
    Point current_point = points[0];
    double accumulated_distance = 0.0;

    cout << fixed << setprecision(5);
    cout << current_point.x << ", " << current_point.y << endl;

    while (accumulated_distance + s <= total_length) {
        accumulated_distance += s;
        double remaining_distance = accumulated_distance;

        for (int i = 0; i < n - 1; i++) {
            if (remaining_distance <= segment_lengths[i]) {
                double ratio = remaining_distance / segment_lengths[i];
                double new_x = points[i].x + ratio * (points[i + 1].x - points[i].x);
                double new_y = points[i].y + ratio * (points[i + 1].y - points[i].y);
                current_point = {new_x, new_y};
                cout << current_point.x << ", " << current_point.y << endl;
                break;
            } else {
                remaining_distance -= segment_lengths[i];
            }
        }
    }

    return 0;
}