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;
}
相关推荐
小欣加油27 分钟前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
Selina K31 分钟前
C中日历时间转换
c语言·开发语言
.千余1 小时前
【C++】手写双向链表:list容器模拟实现
开发语言·c++·笔记·学习·其他
liulilittle1 小时前
过冲:拥塞控制的呼吸与盲行
linux·网络·c++·tcp/ip·计算机网络·tcp·通信
caimouse2 小时前
Reactos 第 3 章 内存管理 — 【中篇】Hyperspace、系统空间、API 与异常
c语言·开发语言·windows·架构
ysu_03142 小时前
leetcode数据结构与算法1~4
c语言·数据结构·学习·算法·leetcode
小欣加油2 小时前
leetcode2574 左右元素和的差值
数据结构·c++·算法·leetcode·职场和发展
weixin_461769402 小时前
通过数组和队列构造二叉树方法(用于算法测试),C++ vector不能直接使用null
数据结构·c++·算法·vector·nullptr·null
caimouse2 小时前
Reactos 第 4 章 对象管理 — 4.1 对象与对象目录
服务器·c语言·开发语言·windows·架构
千寻girling2 小时前
一周没跑步了 ,今日跑步 5KM , 哑铃+健身 20min , 俯卧撑 30 个 ;
数据结构·c++·python·算法·leetcode·职场和发展·线性回归