Cod sursa(job #1074218)

Utilizator Juve45UAIC Alexandru Ionita Juve45 Data 7 ianuarie 2014 13:03:48
Problema Infasuratoare convexa Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.24 kb
#include <fstream>
#include <vector>
#include <iomanip>
#include <cmath>
#include <algorithm>
//#include <iostream>

#define dmax 120002
#define inf 1000000006

using namespace std;

ifstream fin("infasuratoare.in");
ofstream fout("infasuratoare.out");

struct point
{
    double x,y;
};

vector <point> v(dmax);
vector <point> hull;
point a,b;
int n;
double s;

//functions declaration

void read();
//reads the input file

double area(point x1, point x2, point x3);
// calculates the area of the triangle formed by the two points x1 & x2 with the origin O(0,0)

void first();
// replaces the first element form the vectorwith the first element from the left;

bool compare(point p1, point p2);
// compares the two polar angles

double polar(point p1);
// returnes the polar angle of the point p1

void write();
//END of declarations

int main()
{
    read();
    first();
    a=v[0];
    sort(v.begin()+1, v.begin()+n, compare);
    hull.push_back(a);
    hull.push_back(v[1]);
    for(int i=2; i<n; i++)
    {
        while(area(hull[hull.size()-2],hull[hull.size()-1],v[i])>0 && hull.size()>2)
            hull.pop_back();
        hull.push_back(v[i]);
    }
    write();
    return 0;
}


void read()
{
    fin>>n;
    for(int i=0; i<n; i++)
        fin>>v[i].x>>v[i].y;
}


double area(point p1, point p2, point p3)
{
    return (p1.x*p2.y+p1.y*p3.x+p2.x*p3.y-p2.x*p1.y-p1.x*p3.y-p3.x*p2.y)/2;
}
bool compare(point p1, point p2)
{
    return (polar(p1)>polar(p2));
}

void first()
{
    point d;

    d.x=inf;
    d.y=-inf;
    int poz=0;

    for(int i=0; i<n; i++)
    {
        if(v[i].x<d.x)
        {
            d=v[i];
            poz=i;
        }
        else if(v[i].x==d.x) if(v[i].y>d.y)
            {
                d=v[i];
                poz=i;
            }
    }
    v[poz]=v[0];
    v[0]=d;

}

double polar(point x1)
{
    point p1;
    p1.x=x1.x-a.x;
    p1.y=x1.y-a.y;
    return p1.y/(sqrt(p1.y*p1.y+p1.x*p1.x));
}


void write()
{
    fout<<hull.size()<<'\n';
    fout<<fixed<<setprecision(6)<<hull[0].x<<' '<<hull[0].y<<'\n';
    for(int i=hull.size()-1; i>0; i--)
        fout<<fixed<<setprecision(6)<<hull[i].x<<' '<<hull[i].y<<'\n';

}