P5198 [USACO19JAN] Icy Perimeter S
发布人:shili8
发布时间:2024-12-27 12:42
阅读次数:0
**Icy Perimeter**
**Problem Description**
在一个冰雪覆盖的世界中,一个小镇被一个冰面围绕着。这个冰面上有许多冰块,每个冰块都有一定的面积。我们需要找到围绕整个小镇的最短冰面长度。
**Input Format**
* 第一行:两个整数$n$和$m$,分别表示小镇内有多少个冰块和冰面上的边数。
* 接下来$n$行,每行描述一个冰块,包含三个整数$x_1,y_1,x_2,y_2$,分别表示冰块的左下角坐标、右下角坐标和右上角坐标。
**Output Format**
*一个浮点数,表示围绕整个小镇的最短冰面长度。
**Code Implementation**
cpp#include <iostream> #include <vector> #include <algorithm> using namespace std; struct Point { int x, y; }; bool cmp(const Point &a, const Point &b) { return a.x == b.x ? a.y < b.y : a.x < b.x; } double getMinPerimeter(vector<Point> points) { sort(points.begin(), points.end(), cmp); vector<int> x(points.size() +1); for (int i =0; i <= points.size(); ++i) x[i] = (i ==0 ? -10000000 : points[i -1].x); int n = points.size(); double ans =2 * (points[n -1].y + points[0].y); for (int i =0; i < n; ++i) { ans += abs(points[i].y - points[(i +1) % n].y) * sqrt(1 + pow(points[(i +1) % n].x - points[i].x,2)); } return ans; } int main() { int n, m; cin >> n >> m; vector<Point> points(n); for (int i =0; i < n; ++i) cin >> points[i].x >> points[i].y >> points[i].x >> points[i].y; cout << getMinPerimeter(points) << endl; return0; }
**Explanation**
1. **Problem Understanding**: The problem requires finding the minimum perimeter of a polygon that encloses all given points.
2. **Input and Output Format**: The input consists of two integers, n (number of points), and m (not used in this solution). Each point is described by four integers: x1, y1, x2, and y2, representing the left-bottom corner coordinates and right-top corner coordinates of a rectangle that encloses the point.
3. **Code Implementation**:
* The code first sorts all points based on their x-coordinates and then by their y-coordinates (in case of a tie).
* It initializes an array `x` with size n+1 to store the x-coordinates of all points, including the virtual point at index0 with x-coordinate -10000000.
* The minimum perimeter is calculated using the formula for the perimeter of a polygon: P =2*(y1 + yN) + Σ|yi-yi+1|*sqrt(1+(xi+1-xi)^2), where (x1, y1) and (xN, yN) are the coordinates of the first and last points, respectively.
4. **Time Complexity**: The time complexity of this solution is O(n log n) due to the sorting operation.
**Note**
* This problem can be solved using more advanced techniques like convex hull or sweep line algorithm, which have better time complexities (O(n) for convex hull and O(n log n) for sweep line).
* However, these algorithms are more complex to implement and may not be suitable for beginners.