题意:一只蚂蚁,只会向前或左转,现在给出平面上很多个点,从y坐标最小的点开始,求解一种走法,能使得蚂蚁能经过的点最多,每个顶点该蚂蚁只能经过一次,且所行走的路线不能发生交叉。
题解:极角排序
先找到题目要求的起点,然后对剩下的点进行极角排序,让极角最小的点作为起点,再对剩下的进行极角排序,一直迭代。
极角排序:利用叉积,看向量p1和p2的叉积(p1, p2)是否小于零,根据右手定则,是则说明p1在p2逆时针方向,即p1的极角比p2的大;极角相同则按离p0的距离升序排序。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
//极角排序(叉积)
struct Node {
int x, y, id;
Node() {}
Node(int id, int x, int y):id(id),x(x),y(y) {}
}p[55];
int pos; //基准点
int cross(Node p0, Node p1, Node p2) {
return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y);
}
int dis(Node p1, Node p2) {
return (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y);
}
bool cmp(Node p1, Node p2) {
int tmp = cross(p[pos], p1, p2);
if (tmp > 0) return true;
else if (tmp == 0 && dis(p[pos], p1) < dis(p[pos], p2)) return true;
else return false;
}
int t, n, id, x, y;
vector<int> ans;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
ans.clear();
for (int i = 1; i <= n; i++) {
scanf("%d%d%d", &id, &x, &y);
p[i] = Node(id, x, y);
if (p[i].y < p[1].y) swap(p[1], p[i]);
}
ans.push_back(p[1].id);
pos = 1;
for (int i = 2; i <= n; i++, pos++) {
sort(p + i, p + n + 1, cmp);
ans.push_back(p[i].id);
}
int siz = ans.size();
printf("%d", siz);
for (int i = 0; i < siz; i++) {
printf(" %d", ans[i]);
}
printf("\n");
}
return 0;
}