相离的圆(51Nod-1278)
题目
平面上有N个圆,他们的圆心都在X轴上,给出所有圆的圆心和半径,求有多少对圆是相离的。
例如:4个圆分别位于1, 2, 3, 4的位置,半径分别为1, 1, 2, 1,那么{1, 2}, {1, 3} {2, 3} {2, 4} {3, 4}这5对都有交点,只有{1, 4}是相离的。输入
第1行:一个数N,表示圆的数量(1 <= N <= 50000)
第2 - N + 1行:每行2个数P, R中间用空格分隔,P表示圆心的位置,R表示圆的半径(1 <= P, R <= 10^9)输出
一行包含一个整数表示最少教室的个数。输出共有多少对相离的圆。
输入样例
4
1 1
2 1
3 2
4 1输出样例
1
思路:二分
由于所有坐标都在 x 轴上,因此可以将相离问题转化为线段相交问题。
由于求的是圆相离的情况,那么转化后即为求线段不相交的情况,可以将线段的终点按升序排列,如果终点相等的话按起点升序,然后二分查找每一个起点,找到终点大于起点的下标,每次统计下标即可
源程序
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 100000+5;
const int dx[] = {-1,1,0,0};
const int dy[] = {0,0,-1,1};
using namespace std;
struct Node {
LL l,r;
bool operator < (const Node &rhs)const{
if(l==rhs.l)
return r<rhs.y;
return l<rhs.l;
}
} a[N];
LL start[N],endd[N];
int main() {
int n;
while(scanf("%d",&n)!=EOF) {
LL pos,d;
for(int i=1; i<=n; i++) {
scanf("%lld%lld",&pos,&d);
a[i].l=pos-d;
a[i].r=pos+d;
}
for(int i=0; i<n; i++) {
start[i]=a[i+1].l;
endd[i]=a[i+1].r;
}
sort(endd,endd+n);
LL ans=0;
for(int i=0; i<n; i++)
res+=(lower_bound(endd,endd+n,start[i])-(endd));
printf("%lld\n",res);
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效