//堆棋子JAVA import java.util.*; public class Main{ //public static int m = 10^9; //循环边界 public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int n = sc.nextInt(); int[] temp1 = new int[n]; int[] temp2 = new int[n]; //取所有初始棋子的最大边界作为循环边界(这样会超内存),不理解大佬说的为何汇聚点一定在已有棋子的横纵坐标处?? //int maxX = 0; //int maxY = 0; //循环边界 for(int i=0; i<n; i++){ temp1[i] = sc.nextInt(); //循环边界 //maxX = Math.max(maxX,temp1[i]); } for(int i=0; i<n; i++){ temp2[i] = sc.nextInt(); //maxY = Math.max(maxY,temp2[i]); } Point[] point = new Point[n+1]; //棋子的初始位置 for(int i=0; i<n; i++){ point[i+1] = new Point(temp1[i],temp2[i]); } int[] shortDistance = new int[n+1]; //放置i个棋子的最少操作次数 Arrays.fill(shortDistance,Integer.MAX_VALUE); //循环边界没取10^9,只能通过30%;取初始棋子的最大边界,通过60%。取初始棋子下标,100% for(int i : temp1){ for(int j : temp2){ int[] distance = new int[n+1]; //在坐标(i,j)放置k个棋子 for(int k=1; k<=n; k++){ //求出(i,j)到每个初始点的距离,排序 distance[k] = Math.abs(i-point[k].x) + Math.abs(j-point[k].y); } Arrays.sort(distance); int temp = 0; //求若在(x,y)放置1~n个棋子的最短距离,更新结果集合(判断全局最短是否为在(i,j)处获得) for(int k=1; k<=n; k++){ temp += distance[k]; shortDistance[k] = Math.min(shortDistance[k],temp); } } } for(int i=1; i<=n-1; i++){ System.out.print(shortDistance[i] + " "); } System.out.println(shortDistance[n]); } } private static class Point{ int x; int y; Point(int x, int y){ this.x = x; this.y = y; } } }
点赞 评论

相关推荐

点赞 评论 收藏
转发
牛客网
牛客企业服务