1. 程式人生 > >回溯法實現批處理作業排程

回溯法實現批處理作業排程

排列數搜尋問題很簡單,沒做優化。

#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; }