Official

G - Strawberry War Editorial by en_translator


A resulting piece of the cake is a sub-rectangle of the cake, and there are at most \(\frac{H(H+1)W(W+1)}{4}\) possible numbers of strawberries on a piece. Let \(a_1,\ldots,a_X\) be these value.
For each \(i=1,2,\ldots,X\), we find the “minimum possible maximum number \(M\) of strawberries on the resulting pieces when every piece has at least \(a_i\) strawberries.” Then the answer is the minimum \(M-a_i\).
The problem above can be solved with a DP (Dynamic Programming), where \(\mathrm{dp}_{i,j,k,l,m}\) equals “the minimum possible maximum number of strawberries on pieces resulting from cutting a sub-rectangle formed by all \((x,y)\) such that \(i\leq x \lt j, k \leq y \lt l\) into \(m\) pieces (or \(\infty\) if it is impossible),” and the transitions are based on whether to cut the piece vertically or horizontally and how many pieces each part will have.
\(X\) is \(\mathrm{O}(H^2W^2)\), the DP has \(\mathrm{O}(H^2W^2T)\) states, and each transition costs \(\mathrm{O}((H+W)T)\), so the complexity is \(\mathrm{O}((H^5W^4 + H^4W^5)T^2)\). Letting \(N\) be the maximum value of \(H\) and \(W\) and \(N^2\) be the maximum value of \(T\), we have \(\mathrm{O}(N^{13})\). For \(N=6\), this exceeds \(10^{10}\), but the constant factor is small enough, so it is sufficiently fast.
Especially, if we ignore the indices of \(\mathrm{dp}\) where \((j-i+1)(l-k+1) \lt m\), the number of transitions turns out to be about \(10^5\) as follows, so it is indeed fast enough to solve this problem.

#include <bits/stdc++.h>
using namespace std;

int main() {
	
	int sum = 0;
	for(int i=0;i<6;i++){
		for(int j=i+1;j<=6;j++){
			for(int k=0;k<6;k++){
				for(int l=k+1;l<=6;l++){
					int h = j-i;
					int w = l-k;
					for(int m=2;m<=h*w;m++){
						sum += (h-1+w-1) * (m-1);
					}
				}
			}
		}
	}
	cout<<sum<<endl;
	
	return 0;
}

posted:
last update: