2024年华为OD机试真题-计算面积 C/C++解法

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

/// @brief 计算两点组成的面积,保证 point_left 的横坐标 < point_right 的横坐标
/// @param point_left
/// @param point_right
/// @return
static int area_on_2_point(const pair<int, int> &point_left, const pair<int, int> &point_right)
{
    int x_len = point_right.first - point_left.first;
    int y_len = abs(point_left.second - 0);

    return x_len * y_len;
}

// 计算面积
static void HuaWei_OD_test22(void)
{
    int cmd_cnt; // 指令个数
    int x_end;   // 横坐标终点

    vector<pair<int, int>> cmd_vec; // 命令集合
    vector<pair<int, int>> pos_vec; // 坐标集合

    cin >> cmd_cnt >> x_end;

    // 获得命令集合
    for (int i = 0; i < cmd_cnt; i++)
    {
        pair<int, int> tmp;
        cin >> tmp.first >> tmp.second;
        cmd_vec.push_back(tmp);
    }

    // 根据命令集合得到坐标集合

    // 当前坐标
    int current_x = 0;
    int current_y = 0;
    for (int i = 0; i < cmd_cnt; i++)
    {
        current_x = cmd_vec[i].first;
        current_y += cmd_vec[i].second;

        pos_vec.push_back(std::make_pair(current_x, current_y));
    }

    // 计算面积
    int area_sum = 0;
    for (int i = 0; i < cmd_cnt - 1; i++)
    {
        area_sum += area_on_2_point(pos_vec[i], pos_vec[i + 1]);
    }

    // 构造最后一个点(10,0)
    pair<int, int> last_point = {x_end, 0};
    area_sum += area_on_2_point(pos_vec[cmd_cnt - 1], last_point);

    cout << area_sum << endl;
}

int main()
{
    HuaWei_OD_test22();
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值