Suppose that there is a dam near a town.There is big hole on the top of dam as shown in the picture bellow.
The water is going out from this hole with the speed of 1 m2/s and the buildings are going under water. Building roof lengths are 1 m and their height are integer. Given a specific building, we have to calculate a time when the building is 1 meter below the surface of water.
I'm looking for a greedy algorithm to calculate this time.
I thought about it couple of days but I didn't find any good idea.
As I understood the filling will go like this:
Here is algorithm in pseudo-code and descriptions:
1) Let
int h[]
be array with houses height. Index is number of house. So length of array is x-range that we take into account (or number of houses). If there is no house at some position there will be 0 (or house with zero height)Let
float w[]
be array with absolute water height that corresponds withh[]
.I mean that
w[i]-h[i]
= depth of water above i-th houseSo first of all we should:
Step 2) and further will be done every program-calculation step (say 1 sec)
2) Find last index of the local minimum (starting from the left):
3) Count how many houses+water level are equal to local minimum
4) Increment water height on this step (
flow
- is water flow):5) Let
x
be index of the house which we wait to be 1m under water. So decide did we achieve the goal or should we return to step 2):Note
It's possible to optimize the code a little. Still in this form, I think, it's most clear.