贪心算法的C++代码示例
时间: 2023-12-11 13:33:12 浏览: 71
以下是一个贪心算法的C++代码示例,用于求解一个区间覆盖问题:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Interval {
int start;
int end;
Interval(int s, int e) : start(s), end(e) {}
};
bool cmp(const Interval& a, const Interval& b) {
return a.start < b.start;
}
vector<Interval> greedy(vector<Interval>& intervals) {
vector<Interval> res;
if (intervals.empty()) {
return res;
}
sort(intervals.begin(), intervals.end(), cmp);
res.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); ++i) {
if (intervals[i].start <= res.back().end) {
res.back().end = max(res.back().end, intervals[i].end);
} else {
res.push_back(intervals[i]);
}
}
return res;
}
int main() {
vector<Interval> intervals = {Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18)};
vector<Interval> res = greedy(intervals);
for (int i = 0; i < res.size(); ++i) {
cout << "[" << res[i].start << ", " << res[i].end << "]" << endl;
}
return 0;
}
```
阅读全文