Enter the "Basic Training of Deep Search" and step into the palace of C++ algorithms (3)

The third question is this:


       [Search and Backtracking Algorithm] Work Allocation Problem (Standard IO)

Time limit: 1000 ms Space limit: 262144 KB Specific limits

Topic description:

Suppose n pieces of work are assigned to n people. The cost required to assign job i to person j is cij. Try to design an algorithm that assigns a different job to each person and minimizes the total cost. Design an algorithm to calculate the optimal work allocation plan for a given work cost to minimize the total cost.

enter:

There is 1 positive integer n in a row (1≤n≤20). The next n lines have n numbers in each line, and the i-th line represents the various work expenses of the i-th person.

Output:

Output the calculated minimum total cost

Sample input:

3
4 2 5
2 3 6
3 4 5

Sample output:

9

Xiaohang looked at the question and murmured to himself: "It should be possible to solve it like the Queen N problem . "

(For the Queen N problem, please see "In-depth Search Basic Training" and Step into the Palace of C++ Algorithms (2) for details_aliyonghang's blog-CSDN blog )

"Everyone is used as a chess piece, each job is used as a column, and funds are used as a comparison method. If you try again and again, you will be able to try it out! In addition, set a temporary labor fee and the final public fee for comparison output. In this way, you can use search" , as he spoke, he typed the keyboard enthusiastically.

#include<iostream>
using namespace std;
const int MAX=999999999;
int q=MAX,n,c[25][25],b[25];
void dg(int x,int ps)
{
	if(x>n)
	{
		if(ps<q) q=ps;
		return;
	}
	else
	{
		for(int i=1;i<=n;i++)
		{
			if(b[i]==0)
			{
				b[i]=1;
				dg(x+1,ps+c[i][x]);
				b[i]=0;
			}
		}
	
	}
}
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cin>>c[i][j];
		}
	}
	dg(1,0);
	cout<<q;
}

However, the result is:

I have no choice but to modify it.

#include<bits/stdc++.h>
using namespace std;
int n,a[25][1000],b[1000],s,ms=100000,i,j;
void dg(int x)
{
	if(x==n)
	{
		if(s<ms)
			ms=s;
	}
	else if(s<ms)
	{
		for(int i=0;i<n;i++)
		{
			if(!b[i])
			{
				s+=a[x][i];
				b[i]=1;
				dg(x+1);
				b[i]=0;
				s-=a[x][i];
			}
		}
	}
}
int main()
{
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		for(j=0;j<n;j++)
			scanf("%d",&a[i][j]);
	}
	dg(0);
	printf("%d",ms);
	return 0;
} 

Submitting again, Xiaohang got another green and refreshing 100 points! Then, he scrolled the screen again and focused on the next question. To know what happens next, please watch the next episode.

Guess you like

Origin blog.csdn.net/aliyonghang/article/details/122526291