问题描述:
有n份作业分配给n个人去完成,每人完成一份作业。假定第i个人完成第j份作业需要花费cij时间, cij>0,1≦i,j≦n。试设计一个回溯算法,将n份作业分配给n个人完成,使得总花费时间最短。
问题思路:
n分作业分配给n个人,共有A!中排列方式,深度优先遍历其排列数,如果遍历的路径已经比当前最小的话费则舍弃对当前路径的遍历,返回上层节点,寻找合适的路径,即回溯,如果最后可行解比当前的最小话费小,那么就更行最佳的作业安排顺序,同时更新最小的耗费时间。
算法描述:
t :递归的层数
curr :当前的实际时间花费
bestw :当前的最优的时间消耗
arrange:任务的安排
Backtrack(t)
if t>=n
then if curr<bestw
then bestw <- curr
update arrange
ouput(arrange)
else do
for t to n do
swap the arrange of t and i
compute the current cost of the arrange
if curr<bestw then backtrack(t+1)
swap the arrange of t and i
give back the arrange t
数据结构的选择:使用数组是想对任务工作的安排
算法的复杂度分析:O(n!)
算法的实现:
//backtrack.h #include <stdio.h> #include <stdlib.h> #include <limits.h> void backtrack(int t);//t为排列树的深度 void getRslt(char filename[]);//从文件中读取数据,求解结果 void output(int *arrange);//输入最终的任务分配结构 void swap(int &a,int &b);//交换数组中的两个元素 //backtrack.cpp #include "backtrack.h" #include <malloc.h> int *arrange;// 最