平面上有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
这道题思考了好一会,都没有比较好的做法。
学习:
PS:起点和终点放在一个数组中,按大小排序~
排序,令num=圆的个数,遇到起点num--,遇到终点sum+=num
有点神奇。
代码1:
<span style="font-size:24px;">#include"stdio.h"
#include"stdlib.h"
#include"iostream"
#include"algorithm"
using namespace std;
const int maxn=5e4+5;
struct round
{
int dic;
bool lor;//0 起点,1 终点
}r[maxn*2];
bool cmp(const round x,const round y)
{
if(x.dic<y.dic) return true;
if(x.dic==y.dic&&!x.lor) return true;
return false;
}
int main()
{
int n,len=-1;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
int C,R;
scanf("%d%d",&C,&R);
r[++len].dic=C-R;
r[len].lor=0;
r[++len].dic=C+R;
r[len].lor=1;
}
sort(r,r+len+1,cmp);
int ans=0,num=n;
for(int i=0;i<=len;i++)
{
if(r[i].lor) ans+=num;
else num--;
}
printf("%d\n",ans);
return 0;
} </span>
以下这种做法好。容易想到。(值得学习借鉴比较多)
<span style="font-size:24px;">#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=50000+100;
struct node
{
int l;
int r;
} a[maxn];
int b[maxn];
bool cmp(node x,node y)
{
if(x.l<y.l) return true;
else if(x.l==y.l && x.r<y.r) return true;
return false;
}
int main()
{
ios::sync_with_stdio(false);
int ans,n,i,j,x,r,t1,t2,t3;
cin>>n;
for(i=0;i<n;i++) {
cin>>x>>r;
a[i].l=x-r;
a[i].r=x+r;
}
ans=0;
sort(a,a+n,cmp);
for(i=0;i<n;i++) b[i]=a[i].l;
for(i=0;i<n;i++) {
t1=a[i].r;
t2=upper_bound(b,b+n,t1)-b;
ans+=n-t2;
}
cout<<ans<<endl;
return 0;
}</span>
另外修改步长做法:http://blog.youkuaiyun.com/fool_ran/article/details/41593969