腾讯笔试题_电梯有关问题_思路和初步的算法_討論一上

腾讯笔试题_电梯问题_思路和初步的算法_討論一下
本帖最后由 zhanzongru 于 2009-06-21 19:46:42 编辑
问题如下:
一座楼里没有楼梯,只有一架电梯,电梯一次最多只能乘3人,已知楼共有20层,每层有一个人,每个人都有1~20中唯一的编号,他们要去对应的楼层。
  电梯初始状态:在一楼。
  目标状态:每个人在相应楼层。
试编写一个算法,完成目标状态,而且使电梯移动最小距离。

我的思路:
尽可能让电梯满载运行,而且优先解决远处的需求.使得电梯的运行轨迹类似于一个作往复运动的弹簧由于阻尼最后停下来. 对于正态分布的情况, 电梯最后的状态应接近于中点. 理想情况是对于平均分布的输入集合,电梯的运行层数为每个人的(需行层数+3+3)/3,之所以要加两个3是因为电梯在最初运行和达到目标的时候分别有一段必须空载的距离(在初始状态,电梯至少要运行三层才能装满). 当然对于大量数据来说, 实际运行的効率应该趋近这个最优结果的渐近线.

以下是我的程序:目前只是初步实现了一下.拋磚引玉.
#include <stdio.h>
#include <string.h>

/*
 * The Question:
 *
 *一座楼里没有楼梯,只有一架电梯,电梯一次最多只能乘3人,已知楼共有20层,每层有一个人,
  每个人都有1~20中唯一的编号,他们要去对应的楼层。电梯初始状态:在一楼。目标状态:每个人在相应楼层。
试编写一个算法,完成目标状态,而且使电梯移动最小距离。 
 *
 * ZhanZongru(Z80_AT_whut.edu.cn)
 * 2009,May,30th
 *
 * For the sake of simpliticy.
 *
 * The Building uses a United Kingdom Floor naming fashion.
 * 0-19 Floors.
 * The people in every floor use a United States naming fashion to express their destinations.
 * 1-20 Floors.
 * 
 * In one words, 20 Americans in a UK building...
*/

/*Every floor can content 1 to 20 person.*/
unsigned char FloorContent[20][20];

/*The carrier struct.*/
typedef struct _Carrier{
unsigned char Position_uk;
unsigned char Passager_us[3];
}Carrier;

#define CAR_CAP 3

Carrier theCar;

typedef enum _CurrentDirect{
UP_WARD = 0,
DOWN_WARD
}CurDir;

CurDir theDir = UP_WARD;

unsigned char cur_bottom = 0;
unsigned char cur_top = 19;

unsigned char IsSuccessed = 0;
unsigned long RunFloorCount = 0;

void Run_One_Floor(void);
void LayToFloor(unsigned char pos_uk, unsigned char set_id);
void LoadToCar_Up(unsigned char floor_uk, unsigned char id);
void LoadToCar_Down(unsigned char floor_uk, unsigned char id);
unsigned char JudgeStatus();
unsigned char FloorSize(unsigned char floor_uk);
void ReCalc_Bot_Top(void);
void Show_Status(void);
unsigned char FloorFirstOne(unsigned char floor_uk);
unsigned char Min_Passger_id(void);
unsigned char Max_Passger_id(void);

int main(int argc, char** argv)
{
char input_file[50];
char output_file[50];
FILE* fp=NULL;
int i=0;
int simple_crc=0;

if(argc==1)
{
strcpy(input_file, "input.txt");
strcpy(output_file, "output.txt");
}
else if(argc==2)
{
strcpy(input_file, argv[1]);
strcpy(output_file, "output.txt");

}
else if(argc>=3)
{
strcpy(input_file, argv[1]);
strcpy(output_file, argv[2]);
}
else
{
}

fp = fopen(input_file, "r");
if(fp==NULL)
{
perror("Failed:fopen the input file\r\n");
return -1;