题目
tips:活动事件数为源活动事件数加1【此时考虑代码的情况,第一个活动事件开始时间和结束时间都为0,则活动事件数应为源活动事件加1】
//
// Created by youlingdada youlingdada@163.com on 2021/10/30.
//
#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#define N 100
using namespace std;
typedef struct {
int order;
int s_t; // start time
int e_t; // end time
} Active;
// 比较函数
// 按照最早开始最优
bool compare1(const Active &active, const Active &active1) {
return active.s_t < active1.s_t;
};
// 最早结束最优
bool compare2(const Active &active, const Active &active1) {
return active.e_t < active1.e_t;
};
// .用时最短最优
bool compare3(const Active &active, const Active &active1) {
return (active.e_t - active.s_t) < (active1.e_t - active1.s_t);
};
/* 测试数据,重定向输入到文件
* a.txt内容
12
0 0
1 4
3 5
0 6
5 7
3 8
5 9
6 10
8 11
8 12
2 13
12 14
void test() {
int fd = open("D:\\workspace\\C++\\AlgorithmTest\\resource\\a.txt", O_RDONLY);
dup2(fd, 0);
}
*/
int main() {
// 重定向输入
// test();
// 输入数据
int n;
cin >> n;
Active actives[N];
memset(actives, '\0', sizeof actives);
for (int i = 0; i < n; ++i) {
actives[i].order = i;
cin >> actives[i].s_t >> actives[i].e_t;
}
/**
* 贪心算法
* 1.按照最早开始最优
* 2.最早结束最优
* 3.用时最短最优
*
*/
// 策略一
sort(actives + 1, actives + n, compare1);
vector<Active> res1;
int max = 0; // 最大活动数
int h = 0; // 当前活动数
int temp = 0; // 选中活动的最晚结束时间
for (int i = 1; i < n; ++i) {
if (actives[i].s_t >= temp) {
temp = actives[i].e_t;
res1.push_back(actives[i]);
h++;
}
}
// 判断h 与 max的大小,是否更新max
if (max < h) max = h;
// 策略二
sort(actives + 1, actives + n, compare2);
vector<Active> res2;
temp = h = 0;
for (int i = 1; i < n; ++i) {
if (actives[i].s_t >= temp) {
temp = actives[i].e_t;
res2.push_back(actives[i]);
h++;
}
}
// 判断h 与 max的大小,是否更新max
if (max < h) max = h;
// 策略二
sort(actives + 1, actives + n, compare3);
vector<Active> res3;
temp = h = 0;
for (int i = 1; i < n; ++i) {
if (actives[i].s_t >= temp) {
temp = actives[i].e_t;
res3.push_back(actives[i]);
h++;
}
}
// 判断h 与 max的大小,是否更新max
if (max < h) max = h;
// 输出数据,输入活动号
if (max == res1.size()) {
for (auto item: res1) {
cout << item.order << " ";
}
} else if (max == res2.size()) {
for (auto item: res2) {
cout << item.order << " ";
}
} else {
for (auto item: res3) {
cout << item.order << " ";
}
}
}