There are some glasses with equal capacity as 1 litre. The glasses are kept as follows:
4 5 6
7 8 9 10
You can put water to the only top glass. If you put more than 1-litre water to 1st glass, water overflows and fills equally in both 2nd and 3rd glasses. Glass 5 will get water from both 2nd glass and 3rd glass and so on.
If you have X litre of water and you put that water in a top glass, how much water will be contained by the jth glass in an ith row?
Example. If you will put 2 litres on top. 1st – 1 litre 2nd – 1/2 litre 3rd – 1/2 litre
Each glass contributes to the two glasses down the glass. Initially, we put all water in the first glass. Then we keep 1 litre (or less than 1 litre) in it and move rest of the water to two glasses down to it. We follow the same process for the two glasses and all other glasses till the ith row. There will be i*(i+1)/2 glasses till ith row.
Amount of water in jth glass of ith row is: 0.500000
Time Complexity: O(i*(i+1)/2) or O(i^2) Auxiliary Space: O(i*(i+1)/2) or O(i^2)
This article is compiled by Rahul and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Method 2 (Using BFS Traversal)
we will discuss another approach to this problem. First, we add a Triplet(row, col,rem-water) in the queue which indicates the starting value of the first element and fills 1-litre water. Then we simply apply bfs i.e. and we add left(row+1, col-1,rem-water) Triplet and right(row+1, col+1,rem-water) Triplet into the queue with half of the remaining water in first Triplet and another half into the next Triplet.
Following is the implementation of this solution.
// CPP program for above approach
// Program to find the amount
// of water in j-th glass
// of i-th row
voidfindWater(floatk, inti, intj)
// stores how much amount of water
// present in every glass
floatdp[i+1][2*i + 1];
boolvis[i+1][2*i + 1];
// initialize dp and visited arrays
dp[n][m] = 0;
vis[n][m] = false;
// store Triplet i.e curr-row , curr-col
dp[i] = k;
// we take the center of the first row for
// the location of the first glass
vis[i] = true;
// this while loop runs unless the queue is not empty
// First we remove the pair from the queue
pair<int,int>temp = q.front();
intn = temp.first;
intm = temp.second;
// as we know we have to calculate the
// amount of water in jth glass
// of ith row . so first we check if we find solutions
// for the every glass of i'th row.
// so, if we have calculated the result
// then we break the loop
// and return our answer
if(i == n)
floatx = dp[n][m];
if(float((x-1.0)/2.0) < 0)
dp[n+1][m-1] += 0;
dp[n+1][m+1] += 0;
dp[n+1][m-1] += float((x-1.0)/2.0);
dp[n+1][m+1] += float((x-1.0)/2.0);
vis[n+1][m-1] = true;
vis[n+1][m+1] = true;
dp[i-1][2*j-1] = 1.0;
cout<<"Amount of water in jth glass of ith row is: ";
Please Login to comment...