批处理作业调度问题 回溯法

       题目描述:给定n个作业的集合,每一个作业都有两项任务分别在两台机器上完成,每个作业必须先由机器1处理,然后再由机器2处理。要求对于给定的n歌作业,指定最佳作业调度方案,使其完成时间和达到最小。

                                                                                                                           ----题目出自《计算机算法设计与分析  第3版》王晓东

       代码如下:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define MAX 1000

//global variables
int visited[MAX]={0};  //check whether visited
int t[MAX+1][2]={0};  //the time of every two work
int min_time=INT_MAX;  //the minimum time 
int Fa=0,Fb=0;//the first work,the second work
int f=0;//the final result of a permutation
int n=0;//the numbers of the work
int path[MAX][MAX]={0}; //the result of one choice    Because the time is n!,the room may overflow
int count=1;//the number of all results
int order=1;//the order of one result
int best_choice=0;//the best result among all results
int FACT=0;

//prototype
void back_task(int num);
int fact(int n);
//This program is just a practive and it doesn't deal with the n! large number.

int main()
{
	//declaration
	int i;

	//input
	printf("Please input the number of your work:");	
	scanf("%d",&n);
	
	FACT=fact(n-1);
	for(i=1;i<=n;i++)	
	{
		printf("Please input the %d numbers:",i);	
		scanf("%d %d",&t[i][0],&t[i][1]);
	}
	back_task(1);
	printf("\nThe minimum time is :%d",min_time);
	printf("\nThe all permutation are:\n");
	for(int m=1;m<count;m++)
	{
		for(int j=1;j<=n;j++)
		{
			printf("%d ",path[m][j]);
		}
		printf("\n");
	}
	printf("\n\nThe best choice is:");
	for(int j=1;j<=n;j++)
		printf("%d ",path[best_choice][j]);
	getch();
}

void back_task(int num)
{
	int i=1;

	//the condition of the end of the recursion
	if(num>n)
	{
		if(f<min_time)
		{
			min_time=f;
			best_choice=count;
		}
		count++;  
		return ; 
	}

	for(i=1;i<=n;i++)
	{
		if(visited[i]==0 && f<min_time)	
		{
			if(order==1)
			{
				for(int temp=count;temp<count+FACT;temp++)
				{
					path[temp][order]=i;	
				}
			}
			path[count][order++]=i;//recode the path
			printf("%d order=%d  count=%d\n",path[count][order-1],order-1,count);
			visited[i]=1;
			Fa+=t[i][0];
			int temp=Fb;
			if(Fa<Fb)
				Fb+=t[i][1];
			else
				Fb=Fa+t[i][1];
			f+=Fb;	

			back_task(num+1);
			visited[i]=0;
			Fa-=t[i][0];
			f-=Fb;
			Fb=temp;
			order--;
		}
	}
}


int fact(int n)
{
	if(n==1)
		return 1;
	else
		return n*fact(n-1);
}
             参考资料:《计算机算法与设计  第3版》  王晓东

你可能感兴趣的:(算法,input,Path,作业,permutation,Numbers)