题目:http://www.51nod.com/onlineJudge/submitDetail.html#!judgeId=427658
先将圆的在X轴上左起点按升序排序,再用二分查找第一个起点比待查找圆的终点大的圆(即相离)
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; class circle { int x,r,sta,end; circle(int x, int r) { this.x=x; this.r=r; this.sta=x-r; this.end=x+r; } } public class N1278 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner cin=new Scanner(System.in); int n=cin.nextInt(); circle c[]=new circle[n]; for(int i=0;i<n;i++) c[i]=new circle(cin.nextInt(),cin.nextInt()); Arrays.sort(c,new Comparator<circle>() { public int compare(circle c1,circle c2) { if(c1.sta>=c2.sta) return 1; else return -1; } }); int sum=0; for(int i=0;i<n-1;i++) { int p=search(i,c,n); if(p!=-1) sum+=n-p; } System.out.print(sum); } public static int search(int pos,circle c[],int len) { int key=c[pos].end,begin=pos+1,last=len-1; while(begin<last) { int mid=(begin+last)/2; if(c[mid].sta>key) last=mid; else begin=mid+1; } if(c[begin].sta>key) return begin; else return -1; } }