相离的圆(51Nod-1278)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011815404/article/details/89385901

题目

平面上有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;
}

猜你喜欢

转载自blog.csdn.net/u011815404/article/details/89385901