Sunday, June 7, 2015

UVa 190 - Circle Through Three Points

// UVa 190 - Circle Through Three Points

#include <iostream>
#include <cmath>
#include <stdio.h>
using namespace std;

struct point {
	double x, y;
};

struct line {
	double a, b, c;
};

line points_to_line(point p, point q) {
	line l;
	l.a = p.y - q.y;
	l.b = q.x - p.x;
	l.c = -l.a * p.x - l.b * p.y;
	return l;
}

line perpendicular(line l, point p) {
	line per;
	per.a = -l.b;
	per.b = l.a;
	per.c = -per.a * p.x - per.b * p.y;
	return per;
}

point intersection(line l1, line l2) {
	point p;
	p.y = (l2.c * l1.a - l1.c * l2.a) / (l1.b * l2.a - l2.b * l1.a);
	p.x = (l2.c * l1.b - l1.c * l2.b) / (l1.a * l2.b - l2.a * l1.b);
	return p;
}

double dist(point p, point q) {
	return sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y));
}

point middle(point p, point q) {
	point m = { (p.x + q.x) / 2, (p.y + q.y) / 2 };
	return m;
}

void print(double d) {
	char ch = d < 0 ? '-' : '+';
	printf("%c %.3f", ch, abs(d));
}

int main() {
	point p1, p2, p3;
	while (cin >> p1.x >> p1.y >> p2.x >> p2.y >> p3.x >> p3.y) {
		line side1 = points_to_line(p1, p2);
		line side2 = points_to_line(p2, p3);
		point mid1 = middle(p1, p2);
		point mid2 = middle(p2, p3);
		line per1 = perpendicular(side1, mid1);
		line per2 = perpendicular(side2, mid2);
		point c = intersection(per1, per2);
		double r = dist(c, p1);
		// equation 1
		printf("(x ");
		print(-c.x);
		printf(")^2 + (y ");
		print(-c.y);
		printf(")^2 = %.3f^2\n",r);
		// equation 2
		double e = -2 * c.x;
		double f = -2 * c.y;
		double g = -r * r + c.x * c.x + c.y * c.y;
		printf("x^2 + y^2 ");
		print(e);
		printf("x ");
		print(f);
		printf("y ");
		print(g);
		printf(" = 0\n\n");
	}
	return 0;
}

No comments:

Post a Comment