Embercode
✕
Greedy AlgorithmsQuick quiz

Balloons and intervals

8 questions. Covers Merge intervals and insert an interval.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``cpp #include <algorithm> #include <iostream> #include <utility> #include <vector> using namespace std; int main() { vector<pair<int, int>> balloons{{1, 4}, {5, 9}, {2, 6}}; sort(balloons.begin(), balloons.end(), [](const auto& a, const auto& b) { return a.second < b.second; }); vector<int> shots; for (const auto& [start, end] : balloons) { if (shots.empty() || start > shots.back()) { shots.push_back(end); } } cout << shots.size() << ' ' << shots.back() << '\n'; } ``
  2. 2. This program prints one merged block per line. In the options, a slash marks the start of a new line. What does it print? ``cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; struct Interval { int start; int end; }; int main() { vector<Interval> items{{5, 7}, {1, 2}, {2, 4}, {9, 9}}; sort(items.begin(), items.end(), [](const Interval& a, const Interval& b) { return a.start < b.start; }); vector<Interval> merged; for (const Interval& it : items) { if (merged.empty() || it.start > merged.back().end) { merged.push_back(it); } else { merged.back().end = max(merged.back().end, it.end); } } for (const Interval& m : merged) { cout << m.start << '-' << m.end << '\n'; } } ``
  3. 3. Two balloons are [1, 3] and [3, 5]. The arrow program is changed so that a new arrow is shot when b.start >= shots.back() instead of b.start > shots.back(). How many arrows are shot, and where?
  4. 4. In the proof that the balloon greedy is optimal, why can the first arrow move from its spot x to the smallest right end e1 without popping fewer balloons?
  5. 5. Which statements about the balloon arrow program are true? Pick all that apply.

    Pick every answer that is true.

5 question(s) left on this page.