题解:P12816 [NERC 2021] Connect the Points
lly31415926 · · 题解
题目传送门
题目回顾
题目要求我们在平面上用尽可能短的水平和垂直线段连接三个点,使得这三个点相互连通。线段的总长度应尽可能短,且线段数量不超过 100 条。
解题思路
- 排序点:首先将三个点按 x 坐标排序,方便后续处理。
- 确定中位数 y 值:找到三个点y坐标的中位数,作为水平线的y 坐标。
- 绘制垂直线:从最左和最右的点分别绘制垂直线到水平线。
- 绘制水平线:连接两条垂直线的端点,形成水平线。
- 连接中间点:如果中间的点不在水平线上,绘制一条垂直线将其连接到水平线。
- 然后就可以猛攻代码了
AC 代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Point {
int x, y;
};
bool compareX(const Point &a, const Point &b) {
return a.x < b.x;
}
int main() {
vector<Point> points(3);
for (int i = 0; i < 3; ++i) {
cin >> points[i].x >> points[i].y;
}
// 按x坐标排序
sort(points.begin(), points.end(), compareX);
// 计算y的中位数
vector<int> ys = {points[0].y, points[1].y, points[2].y};
sort(ys.begin(), ys.end());
int y_mid = ys[1];
vector<vector<int>> segments;
// 连接最左和最右的点到水平线
if (points[0].y != y_mid) {
segments.push_back({points[0].x, points[0].y, points[0].x, y_mid});
}
if (points[2].y != y_mid) {
segments.push_back({points[2].x, points[2].y, points[2].x, y_mid});
}
// 添加水平线
segments.push_back({points[0].x, y_mid, points[2].x, y_mid});
// 连接中间的点到水平线
if (points[1].y != y_mid) {
segments.push_back({points[1].x, points[1].y, points[1].x, y_mid});
}
// 输出结果
cout << segments.size() << endl;
for (const auto &seg : segments) {
cout << seg[0] << " " << seg[1] << " " << seg[2] << " " << seg[3] << endl;
}
return 0;
}
边界情况处理
- 所有点在同一水平线或垂直线:直接绘制一条线段连接所有点。
- 点重合:题目保证输入的点两两不同,无需处理。
复杂度分析
- 时间复杂度:O ( 1 ),因为只有三个点,排序和计算中位数都是常数时间。
- 空间复杂度:O ( 1 ),存储固定数量的线段。
- 希望管理员通过 OWO