Soldier

题目: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

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值