http://acm.hdu.edu.cn/showproblem.php?pid=5569
matrix
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
问题描述
给定n∗m(n+m为奇数)的矩阵,从(1,1)走到(n,m)且只能往右往下走,设经过的数为a1,a2...a2k,贡献为a1∗a2+a3∗a4+...+a2k−1∗a2k,求最小贡献。
思路:
当是第奇数步的时候状态转移方程为dp[i][j] = min (dp[i-1][j], dp[i][j-1]);
当是第偶数步的时候状态转移方程为dp[i][j] = min (dp[i-1][j] + g[i-1][j]*g[i][j], dp[i][j-1] + g[i][j-1]*g[i][j]);
处理一次边界就可以了dp[1][1] = 0;
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <queue>
#include <stack>
#include <vector>
#include <map>
using namespace std;
typedef long long LL;
#define N 1010
#define INF 0x3f3f3f3f
#define PI acos (-1.0)
#define EPS 1e-8
#define met(a, b) memset (a, b, sizeof (a))
int dp[N][N], g[N][N];
int main ()
{
int n, m;
while (scanf ("%d %d", &n, &m) != EOF)
{
for (int i=1; i<=n; i++)
for (int j=1; j<=m; j++)
scanf ("%d", &g[i][j]);
for (int i=0; i<=n+1; i++)
for (int j=0; j<=m+1; j++)
dp[i][j] = INF;
for (int i=1; i<=n; i++)
{
for (int j=1; j<=m; j++)
{
if ((i+j)&1)
dp[i][j] = min (dp[i-1][j] + g[i-1][j]*g[i][j], dp[i][j-1] + g[i][j-1]*g[i][j]);
else dp[i][j] = min (dp[i-1][j], dp[i][j-1]);
if (i == 1 && j == 1) dp[i][j] = 0;
}
}
printf ("%d\n", dp[n][m]);
}
return 0;
}