会场安排问题
假设要在足够多的会场里安排一批活动,并希望使用尽可能少的会场。设计一个有效的贪心算法来进行安排。试编程实现对于给定的k个待安排活动,计算使用的最少会场。输入数据中,第一行是k的值,接下来的k行中,每行有2个正整数,分别表示k个待安排活动的开始时间和结束时间,时间以0点开始的分钟计。输出为最少的会场数。
输入数据示例
5
1 23
12 28
25 35
27 80
36 50
输出数据
3
先把各个时间排序,并且标记是开始或者是结束时间,在对排序后的数组进行扫描,遇到开始加一,将最大的数赋值给一个变量,结束减一,结果为这个变量。
代码:
#include <iostream>
using namespace std;
struct node{
int time;
bool boe;
};
void quick(node a[],int left, int right){//快速排序
int i, j;//temp是标志位
node temp, t;
if (left > right)
return;
temp = a[left];
i = left;
j = right;
while (i != j){
while (a[j].time >= temp.time&&i<j){//从j开始往前寻找比标志位小的
j--;
}
while (a[i].time <= temp.time&&i<j){//从i开始往前寻找比标志位大的
i++;
}
if (i<j){//交换
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
a[left] = a[i];//
a[i] = temp;
quick(a,left, i - 1);//
quick(a,i + 1, right);
}
int ActivityNumber(node a[],int b){
int MaxNumber = 0, sum = 0;
for (int i = 0; i<b; i++){
if (a[i].boe == true){//遇到开始时间
sum++;
if (sum>MaxNumber){
MaxNumber = sum;//maxnumber是最大会场数
}
}
else//遇到结束时间
sum--;
}
return MaxNumber;
}
int main()
{
int n;
node a[100];
cout << "请输入开会次数,开始结束时间:" << endl;
cin >> n;
for (int i = 0; i<2 * n; i++){
cin >> a[i].time;
if (i % 2 == 1)
a[i].boe = false;//结束是false
else
a[i].boe = true;
}
quick(a,0, 2 * n-1);
cout << ActivityNumber(a,2 * n) << endl;
return 0;
}
/*5
1 23
12 28
25 35
27 80
36 50*/