UVA_378_Intersecting Lines

<pre name="code" class="cpp">#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<list>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#pragma warning(disable:4996)
using std::cin;
using std::cout;
using std::endl;
using std::stringstream;
using std::string;
using std::vector;
using std::list;
using std::pair;
using std::set;
using std::multiset;
using std::map;
using std::multimap;
using std::stack;
using std::queue;
using std::priority_queue;
class Point
{
public:
	double x, y;
	Point() {}
	Point(const double &X,const double &Y)
	{
		x = X;
		y = Y;
	}
};
class Line
{
public:
	double a, b, c;//ax+by=c
	double x_min, x_max, y_min, y_max;//直線的值域
	Line(const Point &first,const Point &second)
	{
		x_min = std::min(first.x, second.x);
		x_max = std::max(first.x, second.x);
		y_min = std::min(first.y, second.y);
		y_max = std::max(first.y, second.y);
		if (first.x != second.x)//斜率式可行
		{
			b = 1;
			a = -(first.y - second.y) / (first.x - second.x);
			c = first.y + a*first.x;
		}
		else//k->無窮
		{
			b = 0;
			a = 1;
			c = first.x;
		}
	}
	bool lineParallel(const Line&line)//判斷兩直線是否平行
	{
		if (a*line.b - b*line.a==0)
		{
			return true;
		}
		return false;
	}
	bool lineOverlap(const Line&line)
	{
		auto D = a*line.b - line.a*b;
		auto Dx = c*line.b - line.c*b;
		auto Dy = a*line.c - line.a*c;
		if (!D&&!Dx&&!Dy)
		{
			return true;
		}
		return false;
	}
	Point getIntersection(const Line&line)//行列式求兩直線交點
	{
		auto D = a*line.b - line.a*b;
		auto Dx = c*line.b - line.c*b;
		auto Dy= a*line.c - line.a*c;
		return{ Dx / D,Dy / D };
	}
	bool segmentIntersected(const Line &line)
	{
		auto point = getIntersection(line);
		if (point.x >= x_min&&point.x <= x_max
			&&point.y >= y_min&&point.y <= y_max
			&&point.x >= line.x_min&&point.x <= line.x_max
			&&point.y >= line.y_min&&point.y <= line.y_max
			)//交點在兩線段的值域內
		{
			return true;
		}
		return false;
	}
};
class Rectangle
{
public:
	int left, right, top, bottom;
	bool inRectangle(const Point &point)
	{
		if (point.x >= left&&point.x <= right&&point.y >= bottom&&point.y <= top)
		{
			return true;
		}
		return false;
	}
};
int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	cout << "INTERSECTING LINES OUTPUT" << endl;
	int n;
	while (cin >> n)
	{
		while (n--)
		{
			double x1, y1, x2, y2, x3, y3, x4, y4;
			cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4;
			Line line1({ x1,y1 }, { x2,y2 }), line2({ x3,y3 }, { x4,y4 });
			if (line1.lineParallel(line2))
			{
				if (line1.lineOverlap(line2))
				{
					cout << "LINE" << endl;
				}
				else
				{
					cout << "NONE" << endl;
				}
			}
			else
			{
				auto point = line1.getIntersection(line2);
				cout << "POINT ";
				printf("%.2lf %.2lf",point.x,point.y);
				cout << endl;
			}
		}
	}
	cout << "END OF OUTPUT" << endl;
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章