Approach
I was thinking that this problem is the same as: giving a list of [start, end, height] rectengle, and you need to find hte value that cut them in half, and this is the line swepping algorithm (in Code-1)
I also saw another interesting approach is to use the binary search (actually serach on answer) within a given error rnage (implemented in Code-2)
Code-1: Line sweeping
class Solution {
public:
double separateSquares(vector<vector<int>>& squares) {
int n = squares.size();
double totalArea = 0;
for_each(squares.begin(), squares.end(), [&](auto& v){totalArea += (double)v[2]*v[2];});
totalArea /= 2;
map<int, int> trigger; // coord(Y) -> weight.
for(int i = 0 ; i < n ; ++i) {
int start = squares[i][1];
int end = squares[i][1] + squares[i][2];
int height = squares[i][2];
trigger[start] += height;
trigger[end] -= height;
}
int curH = 0;
int curY = -1;
int prevY = -1;
for(const auto& e: trigger) {
curY = e.first;
double curArea = (double) (curY - prevY) * curH;
totalArea -= curArea;
if(totalArea <= 0) break;
curH += e.second;
prevY = curY;
}
return curY + totalArea / curH;
}
};
Code-2: Binray search within error
class Solution {
public:
double separateSquares(vector<vector<int>>& squares) {
double totalArea = 0;
for_each(squares.begin(), squares.end(), [&](auto& v){totalArea += (double)v[2]*v[2];});
totalArea /= 2;
double l = 0;
double r = 1'000'000'000;
while(r - l >= 1e-5) {
double m = l + (r - l) / 2;
if(getAreaBelow(squares, m) < totalArea) {
l = m;
} else {
r = m;
}
}
return l;
}
inline double getAreaBelow(const vector<vector<int>>& squares, double h) {
double area = 0;
for(const auto& sq: squares) {
if(double(sq[1]) >= h) continue;
if(double(sq[1]+sq[2]) <= h) {
area += (double)sq[2]*sq[2];
} else {
area += double(h-sq[1])*sq[2];
}
}
return area;
}
};