还是凸包,只不过常规的求法第一步是找最左下的点,而这题是找最左上的点。实质没有不同。
#include<iostream>
#include<algorithm>
#include<cmath>
#define PI 3.141592653
using namespace std;
typedef struct{
int x, y;
} POINT;
POINT ch[100];
double dist(POINT a, POINT b){
return sqrt(pow(a.x - b.x, 2.0) + pow(a.y - b.y, 2.0));
}
int crossProduct(POINT o, POINT a, POINT b){
return (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y);
}
bool cmp_position(POINT a, POINT b){
return a.y > b.y || (a.y == b.y && a.x < b.x);
}
bool cmp_angle(POINT a, POINT b){
int temp = crossProduct(ch[0], a, b);
if(temp == 0)
return (dist(a, ch[0]) < dist(b, ch[0]));
else
return temp < 0;
}
void print(POINT a[], int N){
for(int i = 0; i < N; i++)
cout << a[i].x << " " << a[i].y << endl;
}
int main(){
int P;
cin >> P;
while(P--){
int caseNo, N;
cin >> caseNo >> N;
for(int i = 0; i < N; i++)
cin >> ch[i].x >> ch[i].y;
swap(ch[0], *min_element(ch, ch + N, cmp_position));
sort(ch + 1, ch + N, cmp_angle);
// print(ch, N);
ch[N] = ch[0];
POINT s[100];
int top = 2;
s[0] = ch[0];
s[1] = ch[1];
for(int i = 2; i <= N; i++){
while(top >= 2 && crossProduct(s[top - 2], s[top - 1], ch[i]) >= 0){
top--;
}
s[top++] = ch[i];
}
top--;
if(top == 1)
s[top++] = ch[N - 1];
cout << caseNo << " " << top << endl;;
print(s, top);
}
}