Assignment problem backtracking

Problem Description

Suppose there are n tasks for the k-th parallel working machine. I need time to complete the task of ti. Try to design an algorithm to find the optimal schedule completion of the n tasks, so that the earliest time to complete all tasks.

Entry

3
10 2 3
2 3 4
3 4 5

Export

9
2 4 3

Ideas:

For this input and output, the optimal value is 9, but there will be more optimal solution, I export one.
The final sequence is a binary tree traversal.

For this sample input process is this:

First time:
3 3 individual assigned to work, first try the first assignment to the first person (left node), recursively on this basis, then assign the work to the second of these three individuals in a person's when not assigned to the first person (a person can not have two working), as it has been allocated. Then assigned to the second person, and then as the last person assigned to work for conditions. If the current cost is less than optimal solution, then update the optimal solution.
Second:
selected above is assigned to the first person, second person this time I choose to give (back). Then continue recursively ...

After traversing this several times, constantly update the optimal value, save the optimal solution, the final output can be.

C ++ code

#include <iostream>
#include<bits/stdc++.h>
#define N 100
#define inf 1000000
using namespace std;
int n;
//保存数据
int arr[N][N];
//最优值
int bestc=inf;
//当前的费用
int currentc=0;
//记录最优解 最终的分配情况
int bestflag[N];
int flag[N];
void Backtrack(int num)
{
    if(num==n)
    {
        if(currentc<=bestc)
        {
            bestc=currentc;

            for(int i=0;i<n;i++)
            {
                bestflag[i]=flag[i];
            }
        }
    }
    else
    {
        for(int i=0; i<n; i++)
        {
            //如果这三个人里面还有谁没分配工作
            if(flag[i]==-1)
            {
                //我就分配给他
                currentc+=arr[num][i];
                flag[i]=num;

                Backtrack(num+1);
                currentc-=arr[num][i];
                flag[num]=-1;
            }

        }

    }


}
int main()
{
    memset(flag,-1,sizeof(flag));
    memset(bestflag,-1,sizeof(bestflag));
    cin>>n;
    for(int i=0; i<n; i++)
        for(int j=0; j<n; j++)
        {
            cin>>arr[i][j];
        }
    Backtrack(0);
     cout<<bestc;
    for(int i=0;i<n;i++)
    {
        cout<<arr[i][bestflag[i]]<<" ";
    }


    return 0;
}

Published 200 original articles · won praise 99 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_43889841/article/details/103393107