matrix
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 410 Accepted Submission(s): 245
Problem Description
Given a matrix with
n
rows and
m
columns (
n+m
is an odd number ), at first , you begin with the number at top-left corner (1,1) and you want to go to the number at bottom-right corner (n,m). And you must go right or go down every steps. Let the numbers you go through become an array
a1,a2,...,a2k
. The cost is
a1∗a2+a3∗a4+...+a2k−1∗a2k
. What is the minimum of the cost?
Input
Several test cases(about
5
)
For each cases, first come 2 integers, n,m(1≤n≤1000,1≤m≤1000)
N+m is an odd number.
Then follows n lines with m numbers ai,j(1≤ai≤100)
For each cases, first come 2 integers, n,m(1≤n≤1000,1≤m≤1000)
N+m is an odd number.
Then follows n lines with m numbers ai,j(1≤ai≤100)
Output
For each cases, please output an integer in a line as the answer.
Sample Input
2 3 1 2 3 2 2 1 2 3 2 2 1 1 2 4
Sample Output
4 8
Source
题解: 这个题目我们可以用很简单的动态规划的方法来做
dp[i][j](i + j是奇数)表示从一开始到ary[i][j]这个格子最小的贡献, dp[i][j] 可以从四个方向转移过来
分别是
dp[i - 1][j - 1] + ary[i - 1][j] * ary[i][j];
dp[i - 1][j - 1] + ary[i][j - 1] * ary[i][j];
dp[i - 2][j] + ary[i - 1][j] * ary[i][j];
dp[i][j - 2] + ary[i][j - 1] * ary[i][j];
我们在这四个值当中取最小的就可以了
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 1010;
const int INF = 0x3f3f3f3f;
int ary[N][N];
int dp[N][N];
void read(int & x) {
x = 0;
char ch;
do {ch = getchar();} while (ch < '0' || ch > '9');
do {
x = x * 10 + ch - '0';
ch = getchar();
} while (ch >= '0' && ch <= '9');
}
int main() {
int n, m;
for (int i = 0; i < N; ++i) dp[i][0] = dp[0][i] = INF;
dp[0][1] = dp[1][0] = 0;
while (~scanf("%d%d", &n, &m)) {
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
read(ary[i][j]);
if ((i + j) & 1) {
dp[i][j] = INF;
if (i >= 2 && j >= 2) dp[i][j] = dp[i - 1][j - 1] + ary[i][j] * min(ary[i - 1][j], ary[i][j - 1]);
if (i >= 2) dp[i][j] = min(dp[i][j], dp[i - 2][j] + ary[i][j] * ary[i - 1][j]);
if (j >= 2) dp[i][j] = min(dp[i][j], dp[i][j - 2] + ary[i][j] * ary[i][j - 1]);
}
}
printf("%d\n", dp[n][m]);
}
return 0;
}