[编程题] 堆棋子
小易将n个棋子摆放在一张无限大的棋盘上。第i个棋子放在第x[i]行y[i]列。同一个格子允许放置多个棋子。每一次操作小易可以把一个棋子拿起并将其移动到原格子的上、下、左、右的任意一个格子中。小易想知道要让棋盘上出现有一个格子中至少有i(1 ≤ i ≤ n)个棋子所需要的最少操作次数.
输入描述:
输入包括三行,第一行一个整数n(1 ≤ n ≤ 50),表示棋子的个数 第二行为n个棋子的横坐标x[i](1 ≤ x[i] ≤ 10^9) 第三行为n个棋子的纵坐标y[i](1 ≤ y[i] ≤ 10^9)
输出描述:
输出n个整数,第i个表示棋盘上有一个格子至少有i个棋子所需要的操作数,以空格分割。行末无空格 如样例所示: 对于1个棋子: 不需要操作 对于2个棋子: 将前两个棋子放在(1, 1)中 对于3个棋子: 将前三个棋子放在(2, 1)中 对于4个棋子: 将所有棋子都放在(3, 1)中
输入例子1:
4
1 2 4 9
1 1 1 1
输出例子1:
0 1 3 10
思路:最后关键的棋子的横坐标和纵坐标肯定是出现过的横坐标和纵坐标
当输入为样例中的输入时,那么最后关键棋子的横坐标必然是1,2,4,9中的一个,纵坐标必然是1
可以用反证法证明,xy轴其实是独立的,先只考虑x坐标,假设把k个棋子堆到x0格子所用的步骤最少,a个棋子初始在x0的左边,b个棋子初始在x0的右边,且这k个棋子到x0-1的步数会更少,b>a的情况,那么x0+1的目标将比x0更优,a>b,那么必然存在横坐标为x0-1的格子,至于a=b,x0-1 和x0的步数是一样的。因此,最终汇聚棋子的x坐标只要在棋子初始的x个坐标中考虑。
public static Integer[] chess_min(Integer[] X, Integer[] Y, Integer n) {
Set<Integer> xAxis = new HashSet<Integer>(Arrays.asList(X)); // 去重
Set<Integer> yAxis = new HashSet<Integer>(Arrays.asList(Y));
List<List<Integer>> centers = new ArrayList<List<Integer>>();
for (Integer x: xAxis) {
for (Integer y: yAxis) { // 所有可能的点组合
List<Integer> distances = new ArrayList<Integer>(); //每个distance中存放了所有棋子到该点的距离
for (Integer i=0; i<n; i++) {
distances.add(Math.abs(X[i]-x) + Math.abs(Y[i]-y));
}
Collections.sort(distances); // 将distance中的数据排序
centers.add(distances); // centers的大小,就是所有可能聚集点的数量
}
}
/*
example:
distance1: 0,1,1,2,3,3,5,6
distance2: 0,1,1,3,4,4,4,5
distance3: 0,1,2,3,3,4,5,7
.....
*/
Integer[] min_step = new Integer[n];
Integer[] sum = new Integer[centers.size()];
for (Integer i=0; i<n; i++) {
for (Integer j=0; j<centers.size(); j++) {
sum[j] += centers.get(j).get(i); // sum[j]一直在更新到达该点的n个棋子所需的距离总和,而且每次更新都确保是最小值,
// 因为distance中已经是排序的
}
min_step[i] = Collections.min(Arrays.asList(sum)); // 最小距离
}
return min_step;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
Integer n = in.nextInt();
Integer[] X = new Integer[n];
Integer[] Y = new Integer[n];
for (Integer i=0; i<n; i++) {
X[i] = in.nextInt();
}
for (Integer i=0; i<n; i++) {
Y[i] = in.nextInt();
}
StringBuilder str = new StringBuilder();
for (Integer i: chess_min(X, Y, n)) {
str.append(i+" ");
}
System.out.println(str.substring(0,str.length()-1));
}
}
}