Given initially a time interval. Every time, we pick the largest interval and split that into two halves. If there is a tie, then we pick the interval with the lowest starting point.
for example - [0,9] first split - P1 [0,4] and P2 [4,9]
For second split : dist(P1) = 3 => if pick P1, new intervals would be [0,2] and [2,4]. dist(P2) = 4 => if pick P2, new intervals are [4, 6] and [6,9] In both the cases, we have to create sub interval of distance 1. So, it's a tie. and, we pick P1 as P1 < P2.
[0,2], [2, 4], [4, 9]
Third Split: [0,2], [2, 4], [4,6], [6,9]
Fourth Split: There is a tie, s0, picked [0,2] [0,1], [1,2], [2,4], [4,6], [6, 9]
Fifth Split: [0,1], [1,2], [2,3], [3,4], [4,6], [6,9]
a possible candidate to be on the top : [4,6]
But, I always get [1,2] on top.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
auto dist{ [](const auto & p) {
return p.second - p.first - 1;
} };
auto comp{
[&dist](const auto & p1, const auto & p2) {
if (abs(dist(p1) - dist(p2)) <= 1) {
return p1.first > p2.first;
}
return dist(p1) < dist(p2);
}
};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> maxQ{comp};
maxQ.push({ 0, 9 }); // initial interval
for (int i{ 0 }; i < 5; ++i) {
auto ii{ maxQ.top() };
maxQ.pop();
int mid = (ii.first + ii.second) / 2;
maxQ.push({ ii.first, mid });
maxQ.push({ mid, ii.second });
}
while (!maxQ.empty()) {
auto& ii{ maxQ.top() };
cout << ii.first << " : " << ii.second << endl;
maxQ.pop();
}
}
I'm getting the following output :
1 : 2
6 : 9
0 : 1
2 : 3
3 : 4
4 : 6
IMO, 1 : 2 interval shouldn't be on top. Could someone help me here, why is it so.