您的位置:首页 > 其它

HDU 1086 You can Solve a Geometry Problem too && 简单几何

2013-10-13 18:46 501 查看
这题有点水,起初我的代码没有考虑平行的直线会算不出来,可是这题却给AC了。。。

题意:给你一百条线段,问这些线段交点的个数,重复交点需要重复计算。

解法:先存下所有线段,然后双重for循环,两两判断是否相交,先求两条线段所在直线是否相交,再判断交点是否在线段上,统计个数。

代码:

#include <iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<cmath>
#include<vector>
#define inf 0x3f3f3f3f
#define Inf 0x3FFFFFFFFFFFFFFFLL
#define pi acos(-1.0)
#define eps 1e-8
using namespace std;

int dcmp(double x)
{
return (x>eps)-(x<-eps);
}

struct Point
{
double x, y;
Point(double x = 0, double y = 0):x(x),y(y){}
bool read() {scanf("%lf%lf",&x,&y);return true;}
Point operator+(const Point& p) const {return Point(x+p.x,y+p.y);}
Point operator-(const Point& p) const {return Point(x-p.x,y-p.y);}
Point operator*(const double p) const {return Point(x*p,y*p);}
bool operator==(const Point& p) const {return !dcmp(x-p.x)&&!dcmp(y-p.y);}
bool  operator<(const Point& p) const {if(!dcmp(x-p.x)) return y<p.y; return x<p.x;}
};

struct Segment
{
Point a, b;
void read() {a.read(); b.read();}
};

inline double Dot(const Point& a, const Point& b) {return a.x*b.x+a.y*b.y;}  //向量的点积
inline double Cross(const Point& a, const Point& b) {return a.x*b.y-a.y*b.x;}//向量的叉积

Point I;
bool onSegment(const Point& p, const Point& a, const Point& b) //判断点是否在线段上(包括端点)
{
return (dcmp(Cross(a-p,b-p))==0&&dcmp(Dot(a-p, b-p))<0)||p==a||p==b;
}

bool getSegmentIntersection(const Point& a, const Point& b, const Point& c, const Point& d)
{
Point v = b-a, w = d-c, u = a-c;        //求线段所在直线交点
if(dcmp(Cross(v,w))==0) return false;
double t = Cross(w,u)/Cross(v,w);
I = a+v*t;
if(onSegment(I,a,b)&&onSegment(I,c,d)) return true; //判断线段是否相交
return false;
}

int main()
{
//freopen("in.txt","r",stdin);
int n;
while(~scanf("%d",&n)&&n)
{
vector<Segment> v;Segment tmp;
for(int i = 0 ; i < n ; ++ i)
{
tmp.read(); v.push_back(tmp);
}
int maxn = 0;
for(int i = 0 ; i < n ; ++ i)
{
for(int j = i + 1 ; j < n ; ++ j)
{
if(getSegmentIntersection(v[i].a,v[i].b,v[j].a,v[j].b))
{
maxn ++;
}
}
}
printf("%d\n",maxn);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  几何