#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)1e18
#define f first
#define s second
mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
int n, m;
const int N = 51;
int dp[N][N][N][N];
int a[N][N];
int val(int l1, int r1, int l2, int r2){
return a[r1][r2] + a[l1 - 1][l2 - 1] - a[l1 - 1][r2] - a[r1][l2 - 1];
}
void Solve()
{
cin >> n >> m;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
cin >> a[i][j];
a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];
}
}
for (int l1 = n; l1 >= 1; l1--){
for (int r1 = l1; r1 <= n; r1++){
for (int l2 = m; l2 >= 1; l2--){
for (int r2 = l2; r2 <= m; r2++){
if (l1 == r1 && l2 == r2) dp[l1][r1][l2][r2] = 0;
else {
int ok = val(l1, r1, l2, r2);
int add = INF;
for (int x = l1; x < r1; x++){
add = min(add, dp[l1][x][l2][r2] + dp[x + 1][r1][l2][r2]);
}
for (int x = l2; x < r2; x++){
add = min(add, dp[l1][r1][l2][x] + dp[l1][r1][x + 1][r2]);
}
dp[l1][r1][l2][r2] = add + ok;
// if (l1 == 1 && r1 == n && l2 == )
}
}
}
}
}
cout << dp[1][n][1][m] << "\n";
}
int32_t main()
{
auto begin = std::chrono::high_resolution_clock::now();
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
// cin >> t;
for(int i = 1; i <= t; i++)
{
//cout << "Case #" << i << ": ";
Solve();
}
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
cerr << "Time measured: " << elapsed.count() * 1e-9 << " seconds.\n";
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
340 KB |
Output is correct |
2 |
Correct |
1 ms |
340 KB |
Output is correct |
3 |
Correct |
1 ms |
328 KB |
Output is correct |
4 |
Correct |
1 ms |
340 KB |
Output is correct |
5 |
Correct |
1 ms |
468 KB |
Output is correct |
6 |
Correct |
1 ms |
724 KB |
Output is correct |
7 |
Correct |
1 ms |
1108 KB |
Output is correct |
8 |
Correct |
2 ms |
2516 KB |
Output is correct |
9 |
Correct |
4 ms |
4064 KB |
Output is correct |
10 |
Correct |
4 ms |
4776 KB |
Output is correct |
11 |
Correct |
3 ms |
3540 KB |
Output is correct |
12 |
Correct |
9 ms |
8916 KB |
Output is correct |
13 |
Correct |
15 ms |
11604 KB |
Output is correct |
14 |
Correct |
5 ms |
4300 KB |
Output is correct |
15 |
Correct |
19 ms |
13212 KB |
Output is correct |
16 |
Correct |
4 ms |
6612 KB |
Output is correct |
17 |
Correct |
10 ms |
11348 KB |
Output is correct |
18 |
Correct |
53 ms |
23204 KB |
Output is correct |
19 |
Correct |
82 ms |
24392 KB |
Output is correct |
20 |
Correct |
146 ms |
26460 KB |
Output is correct |