邮局地址

默认分类 · 2023-05-17 · 44 人浏览
import java.util.Scanner;
public class PO {

 public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    int n=in.nextInt();//居民数
    int[] y=new int[n];
    int[] x=new int[n];//居民坐标
    int maxx=100001,minx=-100001,maxy=100001,miny=-100001;
    for(int i=0;i<n;i++){
        x[i]=in.nextInt();
        y[i]=in.nextInt();
        if(x[i]>maxx){
            maxx=x[i];
        }
        if(x[i]<minx){
            minx=x[i];
        }
        if(y[i]>maxy){
            maxy=y[i];
        }
        if(y[i]<miny){
            miny=y[i];
        }
    }
    in.close();
    int minxlenght=1000000,minylenght=1000000,b,a;
    for(int i=minx;i<=maxx;i++){
        int xlenght=0;
        for(int j=0;j<n;j++){
            xlenght+=Math.abs(i-x[j]);
            if(xlenght>minxlenght){
                break;
            }
        }
        if(xlenght<minxlenght){
            minxlenght=xlenght;
            a=i;
        }
    }
    for(int i=miny;i<=maxy;i++){
        int ylenght=0;
        for(int j=0;j<n;j++){
            ylenght+=Math.abs(i-y[j]);
            if(ylenght>minylenght){
                break;
            }
        }
        if(ylenght<minylenght){
            minylenght=ylenght;
            b=i;
        }
    }
    System.out.println(minxlenght+minylenght);
}
}

算法
Theme Jasmine by Kent Liao