會場安排問題(C語言實現)

會場安排問題
貪心算法、貪心策略
題目描述
只有一個會場,輸入總共的場數與開始時間和結束時間,輸出最多能安排的場數。
輸入:
5
1 23
12 24
25 35
36 80
38 50

輸出:
3

思路分析:
爲了安排更多的場數,應該先安排結束早的。結束越早越先安排,這樣可以保證剩餘時間最多,從而使安排的場數最多。使用貪心算法策略通過找到局部最優解從而找到整體最優解。

時間的開始時間和結束時間定義在一個結構體內,方便進行排序與數據處理。既然要先安排先結束的,就需要對輸入的數據進行排序,將右節點(結束時間)比較靠前的放在結構數組的前面。

根據測試數據來看,首先應該安排結束時間最早的【1,,23】這一組,然後界限來應該安排開始時間在 23 之後並且結束時間最早的,即是 【25,35】這一組,以此類推。

下面是AC代碼

#include <stdio.h>

struct Time_S_E{
	int begin;
	int end;
};

int main()
{
	struct Time_S_E time[1000],temp;
	int i=0, j=0, count=1;
	int n;
	printf("Please input the meetting's numbers in total: \n");
	scanf("%d",&n);
	printf("Please input the begin time and end time: \n");
	//input datas
	for(i=0;i<n;++i)
		scanf("%d %d",&time[i].begin, &time[i].end);
	//Sort the right endpoint
	for(j=0;j<n;++j){
		for(i=0;i<n;++i){
			if (time[i].end > time[i+1].end){
				temp = time[i];
				time[i] = time[i+1];
				time[i+1] = temp;
			}
		}
	}
	//output results
	printf("The 1 is on the calender\n");
	for(i=0;i<n;++i){
		if(time[i].end < time[i+1].begin)
			count++;
	}
	printf("%d\n",count);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章