poj 1723!!!

来源:互联网 发布:淘宝售假扣2分多久清零 编辑:程序博客网 时间:2024/06/05 20:47

简单的说这又是一道数学题 :

但是这个数学题我实在是想不到解决的方法了,这个实在是变态啊,为什么,老师在小学的时候不能教一教啊(实在是

太依赖老师了)以后的路还很长,要自力更生啊。



问题描述 :

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.


这个东西让我头疼,我英语实在是不好,但是我在网上找到了这个的大致意思。



有N个士兵,每个士兵站的位置用一个坐标(x,y)表示,现在要将N个士兵站在同一个水平线,即所有士兵的y坐标相同并且x坐标相邻,每个士兵每次可以移动一个位置。求出最少的移动步数。


我是在网上看到的:


首先是 y 坐标相同 ,

每一个坐标y坐标都要移动到同一个位置

设移动之后相同的y坐标是a

y1 -> a

y2 -> a

y3 -> a

.....

mid_a = y[n/2];


其实在这一步的时候,你是不是在想,为什么n/y 不是把所有y 的数值加起来,在除以2,其实在这一步取那个y值都是

一样的,但是为了节省x 的步数,只能取y中间的数值。前提y 的数组要进行排序。


接下来是x 的移动步数,这次就不是把所有的x放到一个点了,而是把所有的x 都相邻,这就不太方便了,我们该如何计算呢 ?


首先要给x 数组全排列,从小到大的顺序。

设x 的起止位置是 a

x[0] -> a

x[1] -> a+1

x[2] -> a+2;

.....

通过上面的式子可以得出:

x[0] - 0 -> a

x[1] - 1 -> a

x[2] - 2 -> a

也就是说,通过上面的式子,就可以把他们推广成 最后移动到同一个位置

xnew[i] = x[i]-i;

现在就是相当于把x数组中的点,全部都移动到同一个点上,所以,取任何的点都是一样的。

mid_xnew = x[n/2];


最后的移动步数就是 = abs(y[i] - mid_y) + abs(xnew[i] - mid_xnew);


 



注 : qsort 的头文件是stdlib.h

qsort 使用方法

用 法: void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));
参数: 1 待排序数组首地址
2 数组中待排序元素数量
3 各元素的占用空间大小
4 指向函数的指针,用于确定排序的顺序






0 0
原创粉丝点击