Soldier

来源:互联网 发布:我的世界pe作弊js 编辑:程序博客网 时间:2024/06/05 15:12

题目:N soldiers of the land Gridland are randomly scattered around the country.
A position in Gridland is given by a pair (x,y) of integer coordinates. Soldiers can move - in one move, one soldier can go one unit up, down, left or right (hence, he can change either his x or his y coordinate by 1 or -1).
The soldiers want to get into a horizontal line next to each other (so that their final positions are (x,y), (x+1,y), …, (x+N-1,y), for some x and y). Integers x and y, as well as the final order of soldiers along the horizontal line is arbitrary.
The goal is to minimise the total number of moves of all the soldiers that takes them into such configuration.
Two or more soldiers must never occupy the same position at the same time.
思路:分别对x,y进行分析。首先士兵要处于同一水平线所以当士兵最后排好队时y要相同。y移动最少的位置就应该y的中位数(求中位数时,要先进行排序)。y[n] -> ym。同理x移动最少的位置也是x的中位数,不过x要求是相邻。x[n]要移动到xm+n上,x[n] -> xm+n=x[n]-n -> xm 这样一来处理的方法就和y类似了。

import java.util.Arrays;import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner input=new Scanner(System.in);        int n=input.nextInt();        int x[]=new int[n];        int y[]=new int[n];        for (int i = 0; i < n; i++) {            x[i]=input.nextInt();            y[i]=input.nextInt();        }        Arrays.sort(x);        Arrays.sort(y);        for (int i = 0; i < n; i++) {            x[i]=x[i]-i;        }        Arrays.sort(x);        int xm=x[n/2];        int ym=y[n/2];        int steps=0;        for (int i = 0; i < n; i++) {            steps+=(Math.abs(x[i]-xm)+Math.abs(y[i]-ym));        }        System.out.println(steps);        // TODO Auto-generated method stub    }}