圆上相交弦问题如下:
解法思路:
- 两条弦相交只需要保证其中一条的一个点在另一条的两个端点之间
- 然后树状数组or线段树维护一下前n个数有多少个左or右端点就好
具体做法:
- 首先读入数据,利用atan2()将坐标转换成弧度;
- 将所有端点存入数组中,按照从小到大排序;还要把端点记录在一个结构体数组中(这样才能知道哪两个端点是对应的);
- 因为要和树状数组结合,而树状数组的下标是1~n的整数,所以接下来利用map将端点的弧度值映射为整数;
- 将结构体数组按照左端点的大小进行排序,然后依次插入每条线段的右端点到树状数组中,每次插入前,查询一次查询树状数组中
相交数ans = 右端点左边一个点在树状数组中的值 - 右端点在数状数组中的值;
- 累加相交数 即为所有的相交弦数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;
}