题意:给定点集,求凸包总长
解题思路:
- 极角排序(自写快排函数SortByAngle在Test case 3出现段错误, 但是自己机器上是可行的,最后用qsort水过)
- Graham Scan
- 求总长
代码:
/*
ID: zc.rene1
LANG: C
PROG: fc
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int N;
double position[10000][3];
int stack[10000];
double mid_x, mid_y;
double temp[3];
void GetInput(FILE *fin)
{
int i;
double sum_x = 0.0, sum_y = 0.0;
fscanf(fin, "%d", &N);
for (i=0; i<N; i++)
{
fscanf(fin, "%lf %lf", &position[i][0], &position[i][1]);
sum_x += position[i][0];
sum_y += position[i][1];
}
mid_x = sum_x / N;
mid_y = sum_y / N;
for (i=0; i<N; i++)
{
position[i][2] = atan2(position[i][1] - mid_y, position[i][0] - mid_x);
}
}
void Swap(int i, int j)
{
memcpy(temp, position[i], 3 * sizeof(double));
memcpy(position[i], position[j], 3 * sizeof(double));
memcpy(position[j], temp, 3 * sizeof(double));
}
int Adjust(int left, int right)
{
int i = left, j = right;
while (i < j)
{
while (i < j && position[j][2] > position[i][2])
{
j--;
}
if (i < j)
{
Swap(i, j);
i++;
}
while (i < j && position[i][2] < position[j][2])
{
i++;
}
if (i < j)
{
Swap(i, j);
j--;
}
}
return i;
}
void SortByAngle(int left, int right)
{
int i;
if (left < right)
{
i = Adjust(left, right);
SortByAngle(left, i - 1);
SortByAngle(i + 1, right);
}
}
int IsGood(int index1, int index2, int index3)
{
double v1[2], v2[2];
double D;
v1[0] = position[index1][0] - position[index2][0];
v1[1] = position[index1][1] - position[index2][1];
v2[0] = position[index3][0] - position[index2][0];
v2[1] = position[index3][1] - position[index2][1];
D = v1[0] * v2[1] - v1[1] * v2[0];
if (D <= 0.0)
{
return 1;
}
else
{
return 0;
}
}
double GetDistance(int index1, int index2)
{
double x1, y1, x2, y2;
x1 = position[index1][0];
y1 = position[index1][1];
x2 = position[index2][0];
y2 = position[index2][1];
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
void GetConvex(FILE *fout)
{
int bottom = -1, top = -1, index1, index2, index3, i;
int good, flag;
double sum = 0.0;
stack[++top] = 0;
stack[++top] = 1;
for (index3=2; index3<N; index3++)
{
while (1)
{
index1 = stack[top - 1];
index2 = stack[top];
if (IsGood(index1, index2, index3))
{
stack[++top] = index3;
break;
}
top--;
}
}
while (1)
{
flag = 1;
index1 = stack[bottom + 1];
index2 = stack[top];
index3 = stack[top - 1];
if (IsGood(index1, index2, index3))
{
top--;
flag = 0;
}
index1 = stack[bottom + 2];
index2 = stack[bottom + 1];
index3 = stack[top];
if (IsGood(index1, index2, index3))
{
bottom++;
flag = 0;
}
if (flag == 1)
{
break;
}
}
for (i=bottom+1; i<top; i++)
{
sum += GetDistance(stack[i], stack[i+1]);
}
sum += GetDistance(stack[top], stack[bottom + 1]);
fprintf(fout, "%.2lf\n", sum);
}
static int cmp(const void *a, const void *b)
{
return ((double *)a)[2] > ((double *)b)[2];
}
int main(void)
{
FILE *fin, *fout;
fin = fopen("fc.in", "r");
fout = fopen("fc.out", "w");
GetInput(fin);
// SortByAngle(0, N-1); test case 3 #11 singal error
qsort(position, N, 3 * sizeof(double), cmp);
GetConvex(fout);
return 0;
}