Cod sursa(job #1469987)

Utilizator andreipnAndrei Petre andreipn Data 10 august 2015 09:00:35
Problema Reuniune Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.31 kb
//http://www.infoarena.ro/problema/Reuniune
#include <iostream>
#include <algorithm>
#include <list>
#include <fstream>

using namespace std;

class Dreptunghi {
public:
	int x0, y0, x1, y1;

	Dreptunghi(): x0(0), y0(0), x1(0), y1(0) {}
	Dreptunghi(int x0, int y0, int x1, int y1): x0(x0), y0(y0), x1(x1), y1(y1) {}

	int perimetru() {
		return 2 * abs(x0 - x1) + 2 * abs(y0 - y1);
	}

	int arie() {
		return abs(x0 - x1) * abs(y0 - y1);
	}
	
	Dreptunghi *intersectie(Dreptunghi o) {
		Dreptunghi *i = new Dreptunghi();
		if (o.x0 >= x1 || o.x1 <= x0)
			return i;
		if (o.y0 >= y1 || o.y1 <= y0)
			return i;
		i->x0 = max(o.x0, x0);
		i->y0 = max(o.y0, y0);
		i->x1 = min(o.x1, x1);
		i->y1 = min(o.y1, y1);
		return i;
	}

	// Rezultatul nu e neaparat un dreptunghi, ci mai degraba
	// un "bounding box" pentru reuniunea celor doua dreptunghiuri
	// cat mai strans posibil.
	Dreptunghi *reuniune(Dreptunghi o) {
		Dreptunghi *r = new Dreptunghi();
		r->x0 = min(x0, o.x0);
		r->y0 = min(y0, o.y0);
		r->x1 = max(x1, o.x1);
		r->y1 = max(y1, o.y1);
		return r;
	}

	friend ostream& operator<< (ostream &out, Dreptunghi &d) {
		out << "(" << d.x0 << "," << d.y0 << "),(" << d.x1 << "," << d.y1 << ")";
		return out;
	}
	friend ostream& operator<< (ostream &out, Dreptunghi *&d) {
		out << *d;
		return out;
	}
};

int main() {
	ifstream ifs("reuniune.in");
	if (!ifs) {
		cerr << "Err deschidere fisier" << endl;
		exit(1);
	}
	int x0, x1, y0, y1;
	ifs >> x0 >> y0 >> x1 >> y1;
	Dreptunghi d1(x0, y0, x1, y1);
	ifs >> x0 >> y0 >> x1 >> y1;
	Dreptunghi d2(x0, y0, x1, y1);
	ifs >> x0 >> y0 >> x1 >> y1;
	Dreptunghi d3(x0, y0, x1, y1);

	Dreptunghi *d12 = d1.intersectie(d2);
	Dreptunghi *d13 = d1.intersectie(d3);
	Dreptunghi *d23 = d2.intersectie(d3);
	Dreptunghi *d123 = d23->intersectie(d1);

	int arie = d1.arie() + d2.arie() + d3.arie() -
	            d12->arie() - d13->arie() - d23->arie() +
	            d123->arie();
	// Calculeaza dreptunghi "bounding box" pentru reuniunea
	// dreptunghiurilor.
	Dreptunghi *r12 = d1.reuniune(d2);
	Dreptunghi *r123 = r12->reuniune(d3);
	int perim = r123->perimetru();

	cout << d1.perimetru();

	ofstream ofs("reuniune.out");
	if (!ofs) {
		cerr << "Err deschidere fisier" << endl;
		exit(1);
	}
	ofs << arie << " " << perim;

	delete d12;
	delete d13;
	delete d23;
	delete d123;
	delete r12;
	delete r123;
	return 0;
}