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

这题有点水,起初我的代码没有考虑平行的直线会算不出来,可是这题却给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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值