以指派问题为例写的一个用循环实现dfs的方法.(gcc)

本文通过一个指派问题的实例,详细介绍了如何使用循环结构来实现深度优先搜索(DFS)的方法,适用于GCC编译环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以指派问题为例写的一个用循环实现dfs的方法.(gcc)


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
	int n, m;
	while(~scanf("%d%d",&n, &m))
	{
		int Eft[n][m], i, j;

		for(i = 0; i < n; ++i) {
			for(j = 0; j < m; ++j) {
				scanf("%d", &Eft[i][j]);
			}	
		} //input efficiency table.

		int Asg[n]; //assignment table.
		int AsgRec[m]; //assignment status record.
		memset(Asg, 0, sizeof(Asg));
		memset(AsgRec, 0, sizeof(AsgRec));
		//init.

		int maxef = 0,tef = 0;

		i = 0; //dfs
		while(i>=0)
		{ 
			while(Asg[i] < m && AsgRec[Asg[i]])
			++Asg[i];

			if(Asg[i] < m) 
			{
				AsgRec[Asg[i]] = 1;
				tef += Eft[i][Asg[i]];

				/*for problems that need to cut brunches,
				the according steps can be placed here.*/

				++i;
				if(i < n)
				{
					Asg[i] = 0;
					continue;
				}
				else
				{
					//summary.
					if(tef > maxef) //renew data.
					{
						maxef = tef;	
						system("clear");
						for(j = 0; j < n; ++j)
						{
							int k;
							for(k = 0; k < m; ++k)
							{
								printf(" %c", k==Asg[j]?'$':'~');
							}
							putchar('\n');
						}
						printf("tef = %d.\n", tef);
					}

					--i;
					tef -= Eft[i][Asg[i]];
					AsgRec[Asg[i]] = 0;
					++Asg[i];
					continue;
				}

			}
			else
			{
				--i;
				if(i >= 0) 
				{
					tef -= Eft[i][Asg[i]];
					AsgRec[Asg[i]] = 0;
					++Asg[i];
				}
				continue;
			}
		} //dfs while-loop.

		printf("the maximum total efficiency is: %d.\n", maxef);
	}//external while-loop.
	return 0;
}//main.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值