hdu 5569 matrix【dp】

来源:互联网 发布:php开发app教程 编辑:程序博客网 时间:2024/06/05 10:38

matrix

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 657    Accepted Submission(s): 374


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 arraya1,a2,...,a2k. The cost is a1a2+a3a4+...+a2k1a2k. What is the minimum of the cost?
 


Input
Several test cases(about 5)

For each cases, first come 2 integers, n,m(1n1000,1m1000)

N+m is an odd number.

Then follows n lines with m numbers ai,j(1ai100)
 


Output
For each cases, please output an integer in a line as the answer.
 


Sample Input
2 31 2 32 2 12 32 2 11 2 4
 


Sample Output
48
 

中文题面:

问题描述
给定n∗mn*mnm(n+mn+mn+m为奇数)的矩阵,从(1,1)(1,1)(1,1)走到(n,m)(n,m)(n,m)且只能往右往下走,设经过的数为a1,a2...a2ka_1, a_2 ... a_{2k}a1,a2...a2k,贡献为a1∗a2+a3∗a4+...+a2k−1∗a2ka_1*a_2+a_3*a_4+...+a_{2k-1}*a_{2k}a1a2+a3a4+...+a2k1a2k,求最小贡献。

一道DP题目,分两种计算方式,+和*。

思路:+的部分是这样的状态转移方程:

dp[i][j]=min(dp[i-1][j],dp[i][j-1]);

*的部分是这样的状态转移方程:

dp[i][j]=min(dp[i-1][j]+a[i-1][j]*a[i][j],dp[i][j-1]+a[i][j-1]*a[i][j]);

这个时候我们判断,如果i+j是奇数的话,这步我们就是乘,相反这步就是+

下边给出完整的AC代码:

#include<stdio.h>#include<string.h>#include<iostream>using namespace std;int a[1004][1004];int dp[1004][1004];int main(){    int n,m;    while(~scanf("%d%d",&n,&m))    {        memset(dp,0x1f1f1f1f,sizeof(dp));        memset(a,0,sizeof(a));        for(int i=1;i<=n;i++)        {            for(int j=1;j<=m;j++)            {                scanf("%d",&a[i][j]);            }        }        int cont=1;        dp[1][1]=0;        for(int i=1;i<=n;i++)        {            for(int j=1;j<=m;j++)            {                if(i==1&&j==1)continue;                if((i+j)%2==1)                {                   dp[i][j]=min(dp[i-1][j]+a[i-1][j]*a[i][j],dp[i][j-1]+a[i][j-1]*a[i][j]);                }                else                {                    dp[i][j]=min(dp[i-1][j],dp[i][j-1]);                }            }        }        printf("%d\n",dp[n][m]);    }}










0 0