1278相离的圆

本文探讨了一道算法题目——计算平面上圆心位于X轴上的圆中相离圆对的数量。介绍了两种解决方案:一种是直接比较每对圆的距离与半径之和,但这种方法时间复杂度过高;另一种是采用改进的贪心算法结合二分查找,大幅提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1278&judgeId=582192

 

1278 相离的圆

基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题

 收藏

 关注

平面上有N个圆,他们的圆心都在X轴上,给出所有圆的圆心和半径,求有多少对圆是相离的。

例如:4个圆分别位于1, 2, 3, 4的位置,半径分别为1, 1, 2, 1,那么{1, 2}, {1, 3} {2, 3} {2, 4} {3, 4}这5对都有交点,只有{1, 4}是相离的。

Input

第1行:一个数N,表示圆的数量(1 <= N <= 50000)
第2 - N + 1行:每行2个数P, R中间用空格分隔,P表示圆心的位置,R表示圆的半径(1 <= P, R <= 10^9)

Output

输出共有多少对相离的圆。

Input示例

4
1 1
2 1
3 2
4 1

Output示例

1

想着两点的距离大于两点的半径之和就相离超时.......

#include<iostream>
#include<algorithm>
#include<string.h>
#define maxn 50050
#define ll long long
using namespace std;
struct node
{
	ll pos;
	ll r;
}ac[maxn];
int main()
{
	ll n,sum=0,q;
	cin>>n;
	for(ll i=0;i<n;i++)
	{
		cin>>ac[i].pos>>ac[i].r;
	}
	for(ll i=0;i<n;i++)
	{
		for(ll j=i+1;j<n;j++)
		{
			q=abs(ac[j].pos-ac[i].pos);
			if(q>(ac[i].r+ac[j].r))
			{
				sum++;
			}
		}
	}
	cout<<sum<<endl;
	return 0;
}

 

o(n^2)不行.....

原来还是贪心的线段问题,看来还是没经验,想用优先队列,可是好像没法统计。。。只能用二分了...

#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
#include<vector>
#define maxn 50050
#define ll long long
using namespace std;
struct node
{
	ll l;
	ll r;
}ac[maxn];
int cmp(node a,node b)
{
	return a.l<b.l;
}
int quick_sort(int l,int r,int x)
{
	while(l<r)
	{
		int mid=(l+r)/2;
		if(ac[mid].l<=x) l=mid+1;
		else  r=mid;
	}
	return l;
}
int main()
{
	ll n,sum=0,q,pos,r;
	cin>>n;
	for(ll i=0;i<n;i++)
	{
		cin>>pos>>r;
		ac[i].l=pos-r;
		ac[i].r=pos+r;
	}
	sort(ac,ac+n,cmp);
	for(int i=0;i<n;i++)
	{
		int ans=quick_sort(i,n,ac[i].r);
		 sum+=n-ans;
	}
	cout<<sum<<endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值