summaryrefslogtreecommitdiffstats
path: root/01-algorithmic_toolbox/02-greedy_algorithms/04-covering_segments
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2016-11-13 19:10:05 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-13 20:30:16 +0100
commit2cf6b010e0a2fb678846d7a2e9ab64d23c49bb7b (patch)
tree79e6a3900fb3a288962cabd572ed942fc77b74c5 /01-algorithmic_toolbox/02-greedy_algorithms/04-covering_segments
parente72410168143db1b79ee30e47d68cca2d730f740 (diff)
downloadcoursera-2cf6b010e0a2fb678846d7a2e9ab64d23c49bb7b.zip
coursera-2cf6b010e0a2fb678846d7a2e9ab64d23c49bb7b.tar.gz
Algorithms : complete 01-algorithmic_toolbox 02-greedy_algorithms
Diffstat (limited to '01-algorithmic_toolbox/02-greedy_algorithms/04-covering_segments')
-rw-r--r--01-algorithmic_toolbox/02-greedy_algorithms/04-covering_segments/covering_segments.cpp34
1 files changed, 26 insertions, 8 deletions
diff --git a/01-algorithmic_toolbox/02-greedy_algorithms/04-covering_segments/covering_segments.cpp b/01-algorithmic_toolbox/02-greedy_algorithms/04-covering_segments/covering_segments.cpp
index c8f1fcd..9067dfe 100644
--- a/01-algorithmic_toolbox/02-greedy_algorithms/04-covering_segments/covering_segments.cpp
+++ b/01-algorithmic_toolbox/02-greedy_algorithms/04-covering_segments/covering_segments.cpp
@@ -9,14 +9,31 @@ struct Segment {
int start, end;
};
-vector<int> optimal_points(vector<Segment> &segments) {
- vector<int> points;
- //write your code here
- for (size_t i = 0; i < segments.size(); ++i) {
- points.push_back(segments[i].start);
- points.push_back(segments[i].end);
- }
- return points;
+bool _sort(Segment i, Segment j)
+{
+ return (i.end <= j.end);
+}
+
+vector<int> optimal_points(vector<Segment> &segments)
+{
+ vector<int> points;
+
+ std::sort(segments.begin(), segments.end(), _sort);
+
+ while (segments.size() > 0) {
+ int v = segments.at(0).end;
+ segments.erase(segments.begin());
+ points.push_back(v);
+
+ for (std::vector<Segment>::iterator it = segments.begin() ; it != segments.end(); ) {
+ if (it->start <= v && it->end >= v) {
+ segments.erase(it);
+ } else
+ it++;
+ }
+ }
+
+ return points;
}
int main() {
@@ -31,4 +48,5 @@ int main() {
for (size_t i = 0; i < points.size(); ++i) {
std::cout << points[i] << " ";
}
+ std::cout << '\n';
}