Description: Suppose you want to arrange a batch of events in enough venues and want to use as few venues as possible. Design an effective greedy algorithm to arrange.
Source code:
#include <iostream>
using namespace std;
struct activity { //结构体,储存每个活动的开始、结束时间,judge用来标记是否已经安排,默认为 0
int start, end;
int judge;
};
int RoomArrange(activity* ac, int n) { //会场安排函数
int room = 0;
int end = 0;
int count = n;
while (count>0) {
for (int i = 0; i < n; i++) {
if ( (ac[i].start > end)&&(ac[i].judge == 0) ) {
end = ac[i].end;
ac[i].judge = 1;
count--;
}
}
room++;
end = 0;
}
return room;
}
int main()
{
int n;
int room;
cout << "Input n:"; //输入待安排活动的规模
cin >> n;
activity* ac = new activity[n]; //动态创建结构体数组,并进行数据初始化输入
cout << "Input " << n << " activities' " << "begin and end:";
for (int i = 0; i < n; i++) {
cin >> ac[i].start >> ac[i].end;
ac[i].judge = 0;
}
/*
冒泡排序,也可以使用其他排序方法,只是为了偷懒...
按照活动的结束时间进行排序
*/
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-1-i; j++) {
if (ac[j].end > ac[j + 1].end) {
activity temp = ac[j];
ac[j] = ac[j + 1];
ac[j + 1] = temp;
}
}
}
room = RoomArrange(ac, n); //会场安排
cout << "Room is :" << room << endl;
return 0;
delete[] ac;
}