会场安排问题(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;
}
发布了22 篇原创文章 · 获赞 39 · 访问量 4041

猜你喜欢

转载自blog.csdn.net/weixin_44895666/article/details/102525786