HDU 5862 Counting Intersections 解题报告

题目链接:Here!

题目大意:给定一些水平或竖直的线段,求它们的交点数。

解题思路:首先想到的方法是暴力枚举线段然后判断是否相交,但是时间复杂度显然过大,所以我们要采取其他的办法。我们把所有水平的线段的两个端点的两个权值分别置为-1和1,然后再按x坐标排序,那么我们只需要面对一个方向上的线段了,这个时候我们就可以将所有竖直的线段按横坐标排序,离散化纵坐标然后按横坐标从小到大依次枚举水平线段的端点,对于每一次枚举我们在线段树插入没有被插入线段树中所有横坐标小于等于当前端点的线段,每次单点查询然后将结果乘上该端点的权值加入答案中即可。虽然前面那种方法看上去很优,但是实际上实现起来比较困难。我们还可以记录所有竖直的线段的端点位置,然后把所有的点按照横坐标排序,按照横坐标从小到大依次枚举,遇到水平线段的左端点就在树状数组中对应位置+1,遇到水平线段的右端点的话就在树状数组中对应位置-1,遇到竖直线段的端点则直接求出对应区间的和加入到答案中。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <list>
#include <deque>
#define LL long long
#define INF 0x3f3f3f3f
#define PII pair<int,int>
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define lowbit(x) (x&(-x))

using namespace std;
const int N = 200005 ;
LL tr[N];
void add(int i,LL x){for(;i<N;i+=lowbit(i))tr[i]+=x;}
LL sum(int i){LL res=0;for(;i>0;i-=lowbit(i))res+=tr[i];return res;}
struct P{
    int x,y1,y2;
    LL f;
}p[N];
LL cal[N];
inline bool cmp(const P& q,const P& w){if(q.x!=w.x)return q.x<w.x;return abs(q.f)>abs(w.f);}
map<int,int>Mp;

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n;
        scanf("%d",&n);
        memset(tr,0,sizeof tr);
        Mp.clear();
        int cnt=1,num=1;
        for(int i=1;i<=n;i++)
        {
            int x1,x2,y1,y2;
            scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
            if(x1==x2)
            {
                if(y1>y2)swap(y1,y2);
                p[cnt++]={x1,y1,y2,0};
                cal[num++]=y1;
                cal[num++]=y2;
            }
            else
            {
                if(x1>x2)swap(x1,x2);
                p[cnt++]={x1,y1,0,1};
                p[cnt++]={x2+1,y1,0,-1};
                cal[num++]=y1;
            }
        }
        sort(cal+1,cal+num);
        int st=1;
        for(int i=1;i<num;i++)
            if(!Mp[cal[i]])Mp[cal[i]]=st++;
        sort(p+1,p+cnt,cmp);
        LL ans=0LL;
        for(int i=1;i<cnt;i++)
            if(p[i].f==0)
                ans+=(sum(Mp[p[i].y2])-sum(Mp[p[i].y1]-1));
            else
                add(Mp[p[i].y1],p[i].f);
        printf("%I64d\n",ans);
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值