matrix
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 327 Accepted Submission(s): 198
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)
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
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 327 Accepted Submission(s): 198
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)
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
题目大意是给你一个矩阵,要你从左上角(1,1)到右下角(n,m),每走两步就要把他们的值相乘,这就是走这两步的费用,然后求最小的总费用
代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#define INF 0x3f3f3f3f
using namespace std;
int a[1001][1005];
int dp[1005][1005];
int n,m;
int main()
{
int i,j,t;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i = 1 ;i <= n; i++)
for(j = 1 ;j <= m; j++)
{
scanf("%d",&a[i][j]);
}
for(i = 0; i <= n; i++)
for(j = 0; j <= m ;j++)
{
dp[i][j] = INF;
}
dp[0][1] = dp[1][0] = 0;
for(i = 2;i <= n; i+=2)
dp[i][1] = dp[i-2][1] + a[i-1][1]*a[i][1];//初始化第一列
for(j = 2;j <= m; j+=2)
dp[1][j] = dp[1][j-2] + a[1][j-1]*a[1][j];//初始化第一行
for(i = 1 ;i <= n; i++)
for(j = 1 ;j <= m; j++)
{
if((i+j)%2==1)
{
if(i>2)dp[i][j] = min(dp[i][j],dp[i-2][j]+a[i][j]*a[i-1][j]);//竖着下方
if(j>2)dp[i][j] = min(dp[i][j],dp[i][j-2]+a[i][j]*a[i][j-1]);//横着右方
if(i>1&&j>1) dp[i][j] = min(dp[i][j],dp[i-1][j-1] + a[i][j]*a[i-1][j] ); //竖着右方
if(i>1&&j>1) dp[i][j] = min(dp[i][j],dp[i-1][j-1] + a[i][j]*a[i][j-1] ); //横着下方
}
}
/*for(i = 1 ;i <= n; i++)
{for(j = 1 ;j <= m; j++)
printf("%d ",dp[i][j]);
printf("\n");
}*/
printf("%d\n",dp[n][m]);
}
return 0;
}