POJ - 3304 Segments(简单几何)

题目链接:点击查看

题目大意:给出n条线段,现在问是否存在一条直线,使得所有线段向这条直线的投影存在一个共同的交点

题目分析:题意有点抽象,需要转换一下,因为所有的线段向某一条直线的投影存在一个交点,那么在那条直线上,从交点位置开始,沿着垂直于直线的方向做另一条直线,会发现这条直线与n条线段都存在一个交点,也就是都相交,这样题目就转换为了是否存在一条直线,使得与n条线段都有交点

因为直线也是由两个点组成的,我们枚举所有线段上的点,作为构成直线上的两个点,每次判断一下是否满足条件即可,时间复杂度为(2*n)*(2*n)*n,因为n比较小,所以直接实现就行了

有个细节需要注意一下,可能会有两个点重合的情况,这个时候需要特判一下

代码:

#include<iostream>
#include<cstdio> 
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<sstream>
using namespace std;
 
typedef long long LL;
 
const int inf=0x3f3f3f3f;

const int N=110;

const double eps = 1e-8;

int n;

int sgn(double x){
	if(fabs(x) < eps)return 0;
	if(x < 0)return -1;
	else return 1;
}

struct Point{
	double x,y;
	Point(){}
	Point(double _x,double _y){
		x = _x;
		y = _y;
	}
	void input(){
		scanf("%lf%lf",&x,&y);
	}
	double distance(Point p){
		return hypot(x-p.x,y-p.y);
	}
	Point operator -(const Point &b)const{
		return Point(x-b.x,y-b.y);
	}
	//叉积
	double operator ^(const Point &b)const{
		return x*b.y - y*b.x;
	}
	//点积
	double operator *(const Point &b)const{
		return x*b.x + y*b.y;
	}
};

struct Line{
	Point s,e;
	Line(){}
	Line(Point _s,Point _e){
		s = _s;
		e = _e;
	}
	void input(){
		s.input();
		e.input();
	}
	//`直线和线段相交判断`
	//`-*this line   -v seg`
	//`2 规范相交`
	//`1 非规范相交`
	//`0 不相交`
	int linecrossseg(Line v){
		int d1 = sgn((e-s)^(v.s-s));
		int d2 = sgn((e-s)^(v.e-s));
		if((d1^d2)==-2) return 2;
		return (d1==0||d2==0);
	}
}line[N];

bool check(Line l)
{
	if(sgn(l.s.distance(l.e))==0)
		return false;
	for(int i=1;i<=n;i++)
		if(!l.linecrossseg(line[i]))
			return false;
	return true;
}

int main()
{
//	freopen("input.txt","r",stdin);
//	ios::sync_with_stdio(false);
	int w;
	cin>>w;
	while(w--)
	{
		vector<Point>point;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			line[i].input();
			point.push_back(line[i].s);
			point.push_back(line[i].e);
		}
		for(int i=0;i<point.size();i++)
			for(int j=0;j<point.size();j++)
				if(check(Line(point[i],point[j])))
				{
					puts("Yes!");
					goto end;
				}
		puts("No!");	
		end:;
	}
 
 
 
 
 
 
 
	
	
	
	
	
	
	
	
	
	return 0;
}
发布了577 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/104093771