AT_joisc2021_a1 曲芸飛行 (Aerobatics) 题解
思路
考虑枚举和贪心。
遍历所有 个检查点,将每个检查点依次作为起始点。
对于每个起始点,使用贪心算法构建飞行路线。每次从当前位置选择下一个未访问的检查点,使得在该点形成的折线角度尽可能大。
使用向量的点积和叉积来计算折线角度。
设三个点 ,向量 ,则夹角 满足 。
最后比较所有以不同起始点构建的路线,选择折线角度最小值最大的路线作为最终结果。
Code
#include<bits/stdc++.h>
using namespace std;
#define int long long
struct Point {
int x, y;
int id;
};
int dotProduct(Point a, Point b, Point c) {
int dx1 = b.x - a.x;
int dy1 = b.y - a.y;
int dx2 = c.x - b.x;
int dy2 = c.y - b.y;
return dx1 * dx2 + dy1 * dy2;
}
int lengthSquared(Point a, Point b) {
int dx = b.x - a.x;
int dy = b.y - a.y;
return dx * dx + dy * dy;
}
double cosAngle(Point a, Point b, Point c) {
return (double)dotProduct(a, b, c) / sqrt((double)lengthSquared(a, b) * lengthSquared(b, c));
}
signed main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int N, Z0;
cin >> N >> Z0;
vector<Point> points(N);
for (int i = 0; i < N; i++) {
cin >> points[i].x >> points[i].y;
points[i].id = i + 1;
}
double maxMinAngle = -1;
vector<int> bestRoute;
for (int start = 0; start < N; start++) {
vector<bool> visited(N, false);
vector<int> route;
route.push_back(start);
visited[start] = true;
for (int step = 1; step < N; step++) {
int current = route.back();
int next = -1;
double maxAngle = -2;
for (int j = 0; j < N; j++) {
if (!visited[j]) {
if (step == 1) {
// 第一次飞行,没有前一个点,直接选择
next = j;
} else {
int prev = route[step - 2];
double angle = cosAngle(points[prev], points[current], points[j]);
if (angle > maxAngle) {
maxAngle = angle;
next = j;
}
}
}
}
route.push_back(next);
visited[next] = true;
}
// 计算当前路线的最小折线角度
double minAngle = 2;
for (int i = 1; i < N - 1; i++) {
int prev = route[i - 1];
int current = route[i];
int next = route[i + 1];
double angle = cosAngle(points[prev], points[current], points[next]);
minAngle = min(minAngle, angle);
}
if (minAngle > maxMinAngle) {
maxMinAngle = minAngle;
bestRoute = route;
}
}
for (int i = 0; i < N; i++)
cout << points[bestRoute[i]].id << '\n';
return 0;
}