HDU 5862 Counting Intersections 解题报告

题目链接:Here!

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

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

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define LL long long
#define INF 0x3f3f3f3f
#define PII pair
#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(;i0;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.xabs(w.f);}
mapMp;

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

你可能感兴趣的:(树状数组)