圆上相交弦 树状数组解法

圆上相交弦问题如下:
在这里插入图片描述
解法思路:

  1. 两条弦相交只需要保证其中一条的一个点在另一条的两个端点之间
  2. 然后树状数组or线段树维护一下前n个数有多少个左or右端点就好

具体做法:

  1. 首先读入数据,利用atan2()将坐标转换成弧度;
  2. 将所有端点存入数组中,按照从小到大排序;还要把端点记录在一个结构体数组中(这样才能知道哪两个端点是对应的);
  3. 因为要和树状数组结合,而树状数组的下标是1~n的整数,所以接下来利用map将端点的弧度值映射为整数;
  4. 将结构体数组按照左端点的大小进行排序,然后依次插入每条线段的右端点到树状数组中,每次插入前,查询一次查询树状数组中 相交数ans = 右端点左边一个点在树状数组中的值 - 右端点在数状数组中的值;
  5. 累加相交数 即为所有的相交弦数ans

代码如下:

#include <iostream>
#include <map>
#include <algorithm>
#include <cmath>
#include <vector>

using namespace std;

const int maxn = 5e5;
int tree[maxn<<1];
int n;

struct node{
    double left, right;
};

node a[maxn];
vector<double> all;
map<double, int> b;

void add(int x, int d){
    while(x <= 2*n){
        tree[x] += d;
        x += (x & -(x));
    }
}

int sum(int x){
    int ssum = 0;
    while(x > 0){
        ssum += tree[x];
        x -= (x & -(x));
    }
    return ssum;
}

bool cmp(node a, node b){
    return a.left < b.left;
}

int main()
{
    cin >> n;
    double x1, x2, y1, y2;
    for(int i = 0; i < n; i++){
        cin >> x1 >> y1 >> x2 >> y2;
        double res1 = atan2(y1, x1);
        double res2 = atan2(y2, x2);
        if(res1 > res2){
            a[i].left = res2;
            a[i].right = res1;
        }
        else{
            a[i].left = res1;
            a[i].right = res2;
        }
        all.push_back(res1);
        all.push_back(res2);
    }
    sort(all.begin(), all.end());
    //映射为整数
    for(int i = 0; i < all.size(); i++)
        b[all[i]] = i+1;
    sort(a,a+n,cmp);
    long long ans = 0;
    for(int i = 0; i < n; i++){
        ans += sum(b[a[i].right]-1) - sum(b[a[i].left]);
        add(b[a[i].right],1);
    }
    cout << ans << endl;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值