Cod sursa(job #710841)

Utilizator mihai_floreaFlorea Mihai Alexandru mihai_florea Data 10 martie 2012 21:05:00
Problema Infasuratoare convexa Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#include <vector>
#include <algorithm>
#include <iomanip>
#include <fstream>
using namespace std;

struct point
{
	double x, y;
	point(double x = 0, double y = 0)
	{
		this->x = x;
		this->y = y;
	}
};

// the cross product of vectors OA and OB
inline double cp(point O, point A, point B)
{
	double x1 = A.x - O.x, y1 = A.y - O.y, x2 = B.x - O.x, y2 = B.y - O.y;
	return x1*y2 - x2*y1;
}

inline double dist2(point A, point B) { return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y); }

struct point_comp
{
	point O;
	point_comp(point O)
	{
		this->O = O;
	}

	bool operator() (point A, point B) { return cp(O, A, B) > 0; } 
};

vector<point> convex_hull(vector<point> p)
{
	if (p.size() < 3)
		return p;

	for (size_t i = 1; i < p.size(); ++i)
		if (p[i]. y < p[0].y || (p[i].y == p[0].y && p[i].x < p[0].x))
			swap(p[0], p[i]);
	
	point_comp cmp(p[0]);
	sort(p.begin() + 1, p.end(), cmp);

	vector<point> q;
	q.push_back(p[0]);
	size_t k = 2;
	while (k < p.size() && cp(p[0], p[1], p[k]) == 0) ++k;
	for (size_t i = 2; i < k; ++i)
		if (dist2(p[i], p[0]) > dist2(p[0], p[1]))
			swap(p[1], p[i]);
	q.push_back(p[1]);
	while (k < p.size() && cp(p[0], p.back(), p[k]) != 0)
		q.push_back(p[k++]);
	while (k < p.size() && cp(p[0], p.back(), p[k]) == 0)
	{
		if (dist2(p[0], p[k]) > dist2(p[0], p.back()))
			swap(p[k], p.back());
		++k;
	}
	q.push_back(p.back());
	p = q;

	p.push_back(p[0]);

	vector<point> ch;
	ch.push_back(p[0]);
	ch.push_back(p[1]);
	int z = 1;

	for (size_t i = 2; i < p.size(); ++i)
	{
		while (cp(ch[z], ch[z-1], p[i]) >= 0)
			ch.pop_back(), --z;
		ch.push_back(p[i]), ++z;
	}
	ch.pop_back();

	return ch;
}

int main()
{
	ifstream fin("infasuratoare.in");
	int N;
	fin>>N;
	vector<point> p(N);
	for (int i = 0; i < N; ++i)
		fin>>p[i].x>>p[i].y;
		
	p = convex_hull(p);
	
	ofstream fout("infasuratoare.out");
	fout<<fixed<<setprecision(6);
	for (vector<point>::iterator it = p.begin(); it != p.end(); ++it)
		fout<<it->x<<" "<<it->y<<"\n";
	
	return 0;
}