https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1278&judgeId=582192
基准时间限制: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;
}