回溯法实现批处理作业调度

排列数搜索问题很简单,没做优化。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int work[4][2]={{0,0},{2,1},{3,1},{2,3}};//可以分段赋值也可以,逐个赋值用,隔开
int n = 3;
int best = 1<<20;
int x[4] = {0,1,2,3};//排列树的初始化
int f[4] = {0};
int bestf[4]={0};
//err:数组赋值错了,work后面的角标没搞清楚,
void backTrack (int t){
    if (t > n){
        int sum = 0;
        for (int i = 1; i <= n; ++i) {
            f[i] = f[i-1] + abs(work[x[i]][0] - work[x[i-1]][1]) + work[x[i]][1];
            sum += f[i];
        }
        if (sum < best ){
            best = sum;
            for (int i = 1; i <= n; ++i) {
                bestf[i] = x[i];
            }
        }
    }
    else{
        for (int i = t; i <= n; ++i) {
            swap(x[t],x[i]);
            //if ()
            backTrack(t+1);
            swap(x[t],x[i]);
        }
    }
}
int main() {
    backTrack(1);
    for (int i = 1; i <= n; ++i) {
        cout << bestf[i] << " ";
    }
    cout << endl;
    cout << best <<endl;
    return 0;
}
    原文作者:回溯法
    原文地址: https://blog.csdn.net/gavinloverqq/article/details/51313458
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞