We can divide this field row-wise or column-wise. If we fix the two parts, the other part is obviously the third part. This can easily be done by using a nested loop. Then we just need to check this three-part with all permutations of A, B, and C. To get the amount of rice in each part efficiently, we need to precalculate the prefix sums of the amount of rice in row-wise and column-wise. From that, we can easily calculate the sum in a range. The overall complexity of this solution is O(n²+m²).