一个任务j在sj开始,并在fj结束;并且每个任务都有权重。
任务相容:任务安排的时间没有重叠
目标:找到最大权重,且相容的任务安排
#include <iostream>
using namespace std;
typedef struct {
int iStartT;
int iFinshT;
int iWight;
}TASK_INFO;
int g_i = 0;
void FindSolution(TASK_INFO *schedule, int **compute, int j, int* path)
{
if (j == 0)
return;
else if (schedule[j - 1].iWight + compute[1][compute[0][j]] > compute[1][j - 1])
{
path[g_i++] = j;
return FindSolution(schedule, compute, compute[0][j], path);
}else
return FindSolution(schedule, compute, j-1, path);
}
int binarySereach(int key, int finsh[], int currentIndex)
{
int low = 1, high = currentIndex;
while (low <= high) {
int mid = (low + high) / 2;
if (key == finsh[mid])
return mid;
else if (key < finsh[mid]) {
high = mid - 1;
if (high < low)
return 0;
}else{
low = mid + 1;
if (low > high)
return high;
}
}
return 0;
}
void DynamicScheduling(TASK_INFO *schedule, int **compute, int taskNum)
{
int* startArray = new int[taskNum+1];
int* finishArray = new int[taskNum+1];
for (unsigned int i = 1; i < taskNum+1; i++)
{
startArray[i] = schedule[i-1].iStartT;
finishArray[i] = schedule[i-1].iFinshT;
}
for (unsigned int j = 1; j < taskNum + 1; j++) {
compute[0][j] = binarySereach(startArray[j], finishArray, j - 1);
if (compute[1][j - 1] > schedule[j-1].iWight + compute[1][compute[0][j]])
compute[1][j] = compute[1][j - 1];
else
compute[1][j] = schedule[j-1].iWight + compute[1][compute[0][j]];
}
delete[] startArray;
delete[] finishArray;
}
int main(){
int taskNum = 0;
cout << "How many tasks would you give? ";
cin >> taskNum;
TASK_INFO *schedule = new TASK_INFO[taskNum];
cout << "Please enter data like this(start_time finish_time weight),such as 1 4 12\n";
for (unsigned int i = 0; i < taskNum; i++)
{
cout << "Enter Task " << i + 1 << " information: ";
cin >> schedule[i].iStartT >> schedule[i].iFinshT >> schedule[i].iWight;
}
//
//用动态算法求解最大权重问题
//compute[2][]:first clow means P(j); second clow means OPT(j)
int **compute = new int*[taskNum+1];
for (unsigned int i = 0; i < 2; i++) //分配内存及置0
compute[i] = new int[taskNum+1];
for (unsigned int i = 0; i < 2; i++)
for (unsigned int j = 0; j < taskNum+1; j++)
compute[i][j] = 0;
DynamicScheduling(schedule, compute, taskNum);
cout << "\n";
for (unsigned int i = 0; i < 2; i++) { //输出P(j)、OPT(j)
if (i == 0)
cout << " P(j): ";
else
cout << "OPT(j): ";
for (unsigned int j = 1; j < taskNum+1; j++)
cout << compute[i][j] << "\t";
cout << "\n";
}
//
//输出任务
int* path = new int[taskNum]; //存储任务的数组
for (int i = 0; i < taskNum; ++i)
path[i] = 0;
FindSolution(schedule, compute, taskNum, path);
cout << "\n最大权重任务:";
for (unsigned int i = 0; i < taskNum && path[i] != 0; i++)
cout << path[i] << "、 ";
for (unsigned int i = 0; i < 2; i++)
{
delete[] compute[i];
}
delete[] compute;
delete[] schedule;
delete[] path;
}