#include <bits/stdc++.h>
using namespace std;
#define int long long
#define sp << ' ' <<
#define nl << '\n'
int n, m;
int g[50][50], dp[50][50][50][50];
int calc(int xa, int ya, int xb, int yb){
if(xa==xb and ya==yb) return dp[xa][ya][xb][yb] = 0;
if(dp[xa][ya][xb][yb]!=-1) return dp[xa][ya][xb][yb];
int sum = g[xb][yb];
if(xa) sum -= g[xa-1][yb];
if(ya) sum -= g[xb][ya-1];
if(xa and ya) sum += g[xa-1][ya-1];
int res = 1e18;
for(int i=xa; i<xb; ++i)
res = min(res, calc(xa, ya, i, yb) + calc(i+1, ya, xb, yb));
for(int i=ya; i<yb; ++i)
res = min(res, calc(xa, ya, xb, i) + calc(xa, i+1, xb, yb));
return dp[xa][ya][xb][yb] = res + sum;
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
cin >> n >> m;
for(int i=0; i<n; ++i){
for(int j=0; j<m; ++j){
cin >> g[i][j];
if(i) g[i][j] += g[i-1][j];
if(j) g[i][j] += g[i][j-1];
if(i and j) g[i][j] -= g[i-1][j-1];
for(int k=0; k<n; ++k)
for(int l=0; l<m; ++l)
dp[i][j][k][l] = -1;
}
}
cout << calc(0, 0, n-1, m-1);
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
364 KB |
Output is correct |
2 |
Correct |
1 ms |
364 KB |
Output is correct |
3 |
Correct |
1 ms |
492 KB |
Output is correct |
4 |
Correct |
1 ms |
364 KB |
Output is correct |
5 |
Correct |
1 ms |
620 KB |
Output is correct |
6 |
Correct |
2 ms |
1260 KB |
Output is correct |
7 |
Correct |
2 ms |
1516 KB |
Output is correct |
8 |
Correct |
11 ms |
4844 KB |
Output is correct |
9 |
Correct |
19 ms |
7276 KB |
Output is correct |
10 |
Correct |
27 ms |
8812 KB |
Output is correct |
11 |
Correct |
23 ms |
7148 KB |
Output is correct |
12 |
Correct |
79 ms |
16620 KB |
Output is correct |
13 |
Correct |
129 ms |
21972 KB |
Output is correct |
14 |
Correct |
37 ms |
8940 KB |
Output is correct |
15 |
Correct |
158 ms |
24812 KB |
Output is correct |
16 |
Correct |
18 ms |
8684 KB |
Output is correct |
17 |
Correct |
66 ms |
17644 KB |
Output is correct |
18 |
Correct |
403 ms |
38380 KB |
Output is correct |
19 |
Correct |
647 ms |
46572 KB |
Output is correct |
20 |
Correct |
749 ms |
49260 KB |
Output is correct |