教室課程排程問題的兩種解法(區間著色問題)

2021-06-11 01:23:43 字數 2407 閱讀 6724

問題描述:假如要用很多個教室對一組課程進行排程,每節課程都有其開始時間和結束時間,我們希望使用盡量少的時間來排程所有的課程,請給出排程演算法?

分析:1、利用貪心演算法來解決這個問題。

1)將課程按照其結束時間的先後順序排序。

2)設課程集合為c,我們可以利用貪心演算法先求出初始課程集合c的乙個最大相容課程子集c1(c包含c1),為集合c1的課程安排乙個教室。

3)將課程集合作為乙個新的集合,進行第1)步操作直到將所有的課程都安排完。

此演算法的時間複雜度是o(n平方

)2、不利用貪心演算法,而是直接根據課程開始的先後順序和相容情況來安排課程。(直接法) 1)

將課程按照其開始時間的先後順序排序。

2)將排好序的課程依次加入教室。對每乙個即將加入的課程的規則如下:

a、從第乙個教室開始檢查。 b、

若未被占用,就使用;若占用了,比較該教室中的最後一門課程的結束時間與將要加入的課程的開始時間,若後者大於等於前者,則將其加入該教室,並更新該教室的最後結束時間。

c、若上乙個教室不能使用,就按照a中的方式檢查下乙個教室

d、按上述方式將所有的課程安排完畢。

此演算法由於只需將課程遍歷一遍,遍歷的時間複雜度為o(n),排序的時間負責度為o(nlogn),故其時間複雜度為o(nlogn)。

c語言實現如下:

檔案「h1.h」

#ifndef h1_h

#define h1_h

#include#include#include#include#include#define maxsize 100

struct class; //0 the other way.

void finishtimequicksort(class c, int n, int flag);

void qsort(class c, int low, int high, int flag);

int partition(class c, int low, int high, int flag);

void classroomdistributiongreedy(class c, int n, int classroom[maxsize]);

void printcoursedistributed(int classroom[maxsize]);

void classroomdistribution(class c, int n, int classroom[maxsize]);

#endif

檔案:"classroomdistribution.cpp"

#include "h1.h"

void timequicksort(class c, int n, int flag)

void qsort(class c, int low, int high, int flag)

}int partition(class c, int low, int high, int flag)

} else

} c[low] = c[high];

if(flag == 1)

flag[k]++;

classroom[k][position[k]] = i; }}

int main();

for(i=0; i<=6; i++)

c[6].starttime=1; c[6].finishtime=3;

c[5].starttime=2; c[5].finishtime=4;

c[4].starttime=3; c[4].finishtime=5;

c[3].starttime=4; c[3].finishtime=6;

c[2].starttime=5; c[2].finishtime=7;

c[1].starttime=6; c[1].finishtime=8; //test values.

c[0].starttime=0; c[0].finishtime=0;//initiate class values.

//timequicksort(c, 6, 0); //sort according to starting time of each course.

//classroomdistribution(c, 6, classroom);//direct strategy.

timequicksort(c, 6, 1);//sort according to finishing time of each course.

classroomdistributiongreedy(c, 6, classroom);//greedy strategy

printcoursedistributed(classroom);

return 0;

}

八皇后問題的兩種解法

八皇后問題,是回溯演算法 的典型案例。該問題是國際西洋棋棋手馬克斯 貝瑟爾於1848年提出 在8x8格的西洋棋 上擺放八個皇后,使其不能互相攻擊,即任意兩個皇后都不能處於同一行 同一列或同一斜線上,問有多少種擺法。高斯認為有76種方案。1854年在柏林 的象棋雜誌上不同的作者發表了40種不同的解,後...

6 2分魚問題兩種解法

分魚問題,從e開始遞推,使用for迴圈簡化中間計算,優化列舉 include using namespace std int main if i 0 已找到答案 break num 0 num 1 4 5 1 for int i 0 i 5 i cout num i return 0 分魚問題,從e...

約瑟夫環問題的兩種解法(詳解)

題目 josephus有過的故事 39 個猶太人與josephus及他的朋友躲到乙個洞中,39個猶太人決定寧願死也不要被敵人抓。於是決定了自殺方式,41個人排成乙個圓圈,由第1個人開始報數,每報數到第3人該人就必須自殺。然後下乙個重新報數,直到所有人都自殺身亡為止。然而josephus 和他的朋友並...