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

cpp 复制代码
#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;
}
相关推荐
RuoZoe1 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
blasit1 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星3 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛4 天前
delete又未完全delete
c++
祈安_5 天前
C语言内存函数
c语言·后端
端平入洛5 天前
auto有时不auto
c++
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20216 天前
信号量和信号
linux·c++
多恩Stone6 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc