Pagini recente » Cod sursa (job #1878300) | Cod sursa (job #16546) | Clasament dinamica_v | Cod sursa (job #774616) | Cod sursa (job #2636741)
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
FILE* fin, * fout;
struct point {
float x, y;
};
vector<point> v;
vector<int> poly;
float cross_product(point origin, point a, point b) {
float x1 = origin.x - a.x;
float x2 = origin.x - b.x;
float y1 = origin.y - a.y;
float y2 = origin.y - b.y;
return (y2 * x1 - y1 * x2);
}
int side(point origin, point end, point p) {
float prod = cross_product(origin, end, p);
if (prod > 0) return 1;
if (prod < 0) return -1;
return 0;
}
float dist(point a, point b) {
float x = a.x - b.x, y = a.y - b.y;
x *= x;
y *= y;
return x + y;
}
void convex_hull() {
auto cmp = [](point& a, point& b) {return (a.x < b.x || (a.x == b.x && a.y < b.y));};
sort(v.begin(), v.end(), cmp);
poly.push_back(0);
bool done = false;
int current = 0, next = 1;
while (!done) {
for (int i = 0;i < v.size();++i) {
if (i == current || i == next) continue;
int s = side(v[current], v[next], v[i]);
if (s > 0)
next = i;
else if (s == 0) {
if (dist(v[current], v[i]) > dist(v[current], v[next]))
next = i;
}
}
if (next == 0)
done = true;
else {
poly.push_back(next);
current = next;
next = 0;
}
}
fprintf(fout,"%i\n", poly.size());
for (int i = poly.size() - 1;i >= 0;--i) {
int j = poly[i];
fprintf(fout,"%f %f\n", v[j].x, v[j].y);
}
}
int main() {
fin = fopen("infasuratoare.in", "r");
fout = fopen("infasuratoare.out", "w");
int n;
fscanf(fin, "%i", &n);
while (n--) {
float x, y;
fscanf(fin, "%f %f", &x, &y);
v.push_back({ x,y });
}
convex_hull();
return 0;
}