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

       题目描述:给定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版》  王晓东

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值