题目链接:点击打开链接
题目大意:
在x轴上有一些圆,给出各个圆的圆心坐标及半径,求这些圆中相离的圆有多少对。
解题思路:
一:对于每一个圆,设其与x坐标轴的作右交点分别为L、R,当两个圆相交时,必然是对应的[L,R]有公共区间,那么问题就转化为了:求在x轴上的一些线段中没有公共区间的线段的对数。
二:O(n*n)的算法就不谈了。
三:我们对所有的区间按左端点排序,对于A区间后面的一个区间B,只要B区间的左端点在A区间的右端点之后,那么A,B区间肯定无公共区间,同样的,B以后的区间更加不会与A区间有公共区间,那么对于区间A,我们只要找出左端点大于A区间右端点的第一个区间,就可以求出与A不相交的区间个数,求和即可,复杂度O(n*logn)。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#define LL long long
using namespace std;
const int maxn=5e4+10;
struct node{
double l,r;
bool operator < (const node &n1)const{
if(l!=n1.l)return l<n1.l;
return r<n1.r;
}
}circle[maxn];
double L[maxn];
int main(){
// freopen("in.txt","r",stdin);
int n;
double o,r;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%lf%lf",&o,&r);
circle[i].l=o-r;
circle[i].r=o+r;
}
sort(circle,circle+n);
int ans=0;
for(int i=0;i<n;i++)L[i]=circle[i].l;L[n]=3e9+1;
for(int i=0;i<n;i++){
int id=upper_bound(L,L+n,circle[i].r)-L;
ans+=n-id;
}
printf("%d\n",ans);
return 0;
}
二分查找用upper_bound()和lower_bound()真的超级舒服
