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 }}
- soldier
- Soldier
- Soldier-types
- uva soldier
- 我看《Soldier》
- but become a soldier
- codeforces546E Soldier and Traveling
- A. Soldier and Bananas
- B. Soldier and Badges
- CF Soldier and Cards
- Codeforces546A:Soldier and Bananas
- Codeforces546B:Soldier and Badges
- Codeforces546C:Soldier and Cards
- C. Soldier and Cards
- Codeforces546C:Soldier and Cards
- hdu5603the soldier of love
- Soldier and Badges
- Soldier and Badges
- opencv形态学操作函数morphologyEx
- webSocket 有点坑
- oracle script
- mybatis中#{}报错 Parameter index out of range (1 > number of parameters, which is 0)问题
- Unity3d热更新全书-加载(二)如何在不用AssetBundle的前提下动态加载预设
- Soldier
- maven-war-plugin
- HIbernate——list和iterator的区别
- linux命令---find
- .net 的登陆验证接口的实现
- 原生拖放
- Android Studio利用Gradle删除没有使用到的资源和代码文件
- json 数据的添加修改
- git 回滚任意版本