looking for an algorithm for Under Water Town

273 Views Asked by At

Suppose that there is a dam near a town.There is big hole on the top of dam as shown in the picture bellow.
city view

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.

1

There are 1 best solutions below

0
On

As I understood the filling will go like this: enter image description here

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 with h[].
I mean that w[i]-h[i] = depth of water above i-th house
So first of all we should:

copy elements from h[] to w[]

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):

i=0;
while(w[i+1]<=w[i]){
    i++;
    if(i == w.length-1) 
        break; // or next step will violate array boundaries
}

3) Count how many houses+water level are equal to local minimum

count = 0;
for(j=0;j<=i;j++)
    if(w[j] == w[i])
        count++;

4) Increment water height on this step (flow - is water flow):

for(j=0;j<=i;j++)
    if(w[j] == w[i])
        w[j] += flow / count;

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):

if (w[x] - h[x] >= 1m)
    return; // we achieved the goal !!!
else
    repeat from step "2)"

Note
It's possible to optimize the code a little. Still in this form, I think, it's most clear.