HDU 3465 Life is a Line 直线相交 逆序数

给个区间和n条不相同的直线 求区间里交点的个数 n<=50000

 

和区间左边交点的顺序映射到右边去就变成了求逆序数的个数

 

注意垂直情况以及排序的第二关键字 每次都忘记维护 然后就wa...

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
const int N=1e5 + 100;
const double eps=1e-7;
int c[N],n,m,num;
int lowbit(int x){return x&-x;}
void updata(int x,int y)
{
    while(x<=n)
    {
        c[x]+=y;
        x+=lowbit(x);
    }
}
int sum(int x)
{
    int res=0;
    while(x)
    {
        res+=c[x];
        x-=lowbit(x);
    }
    return res;
}
int sgn(double x)
{
    if(fabs(x)<eps)return 0;
    if(x>eps)return 1;
    return -1;
}
struct Point{
    double x,y;
    Point(double _x,double _y){x=_x;y=_y;}
    Point(){}
    double operator ^(const Point&p)const
    {
        return x*p.y-y*p.x;
    }
    Point operator -(const Point&p)const
    {
        return Point(x-p.x,y-p.y);
    }
};
struct Line{
    Point s,e;
    Line(Point _s,Point _e){s=_s;e=_e;}
    Line(){}
    double ly,ry;
    int id;
}L[N];
Point operator &(const Line &a,const Line &b)
{
    Point res=a.s;
    double t=((a.s-b.s)^(b.s-b.e))/((a.s-a.e)^(b.s-b.e));
    res.x+=(a.e.x-a.s.x)*t;
    res.y+=(a.e.y-a.s.y)*t;
    return res;
}
bool cmp1(Line a,Line b)
{
    if(sgn(a.ly-b.ly)==0)return a.ry<b.ry;
    return a.ly<b.ly;
}
bool cmp2(Line a,Line b)
{
    return a.ry<b.ry;
}
void init()
{
    memset(c,0,sizeof(c));
}
int main()
{
    int ans,k,m;
    double l,r,x1,x2,y1,y2;
    while(scanf("%d",&n)!=EOF)
    {
        init();
        scanf("%lf%lf",&l,&r);
        Line lef(Point(l,0),Point(l,1));
        Line rig(Point(r,0),Point(r,1));
        k=1;
        m=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
            if(sgn(x1-x2)==0)
            {
                if(sgn(x1-l)>=0&&sgn(x1-r)<=0)
                {
                    m++;
                }
                continue;
            }
            L[k]=Line(Point(x1,y1),Point(x2,y2));
            L[k].ly=(L[k]&lef).y;
            L[k].ry=(L[k]&rig).y;
//            printf("%lf %lf\n",L[k].ly,L[k].ry);
            k++;
        }
        sort(L+1,L+k,cmp1);
        for(int i=1;i<k;i++)
            L[i].id=i;
        sort(L+1,L+k,cmp2);
        ans=0;
        for(int i=1;i<k;i++)
        {
//            printf("%lf %lf\n",L[i].ly,L[i].ry);
            updata(L[i].id,1);
            ans+=sum(k-1)-sum(L[i].id);
        }
        ans+=(k-1)*m;
        printf("%d\n",ans);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值