matrix
Time Limit: 20 Sec
Memory Limit: 256 MB
题目连接
http://acm.hdu.edu.cn/showproblem.php?pid=5569
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)
Output
For each cases, please output an integer in a line as the answer.
Sample Input
2 3
1 2 32 2 12 32 2 11 2 4Sample Output
4
8HINT
题意
给定n*m(n+m为奇数)的矩阵,从(1,1)走到(n,m)且只能往右往下走,设经过的数为a1,a2,..,a2k,贡献为a1*a2+a3*a4...+a2k-1*a2k,求最小贡献
题解:
dp[i][j]表示走到i,j的最小贡献,我们只考虑(i+j)为奇数的时候就好了
然后转移的时候,也只会从奇数位置转移过来
代码:
#include#include #include using namespace std;inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){ if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f;}int n,m;int mp[1005][1005];int dp[1005][1005];const int inf = 1e9+5;int main(){ while(scanf("%d%d",&n,&m)!=EOF) { for(int i=0;i<=n;i++) for(int j=0;j<=m;j++) dp[i][j]=inf; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) mp[i][j]=read(); dp[1][0]=0,dp[0][1]=0; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if((i+j)%2) { dp[i][j]=inf; if(i>1&&j>1) dp[i][j]=min(dp[i][j],dp[i-1][j-1]+min(mp[i-1][j]*mp[i][j],mp[i][j-1]*mp[i][j])); if(i>1) dp[i][j]=min(dp[i][j],dp[i-2][j]+mp[i-1][j]*mp[i][j]); if(j>1) dp[i][j]=min(dp[i][j],dp[i][j-2]+mp[i][j]*mp[i][j-1]); } } } printf("%d\n",dp[n][m]); }}