1. 程式人生 > >想離的圓(排序+二分查找)

想離的圓(排序+二分查找)

for ner earch 題目 circle tde cin end lin

題目: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; } }

想離的圓(排序+二分查找)