matrix
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 437 Accepted Submission(s): 260
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
Recommend
dp[i][j],到(i, j)的最小贡献。
当i+j+1是奇数时,dp[i+1][j] = min(dp[i+1][j], g[i+1][j] * g[i][j]), dp[i][j+1] = min(dp[i][j+1], g[i][j+1] * g[i][j])。
当i+j+1是偶数时,dp[i+1][j] = min(dp[i+1][j], dp[i][j]), dp[i][j+1] = min(dp[i][j+1], dp[i][j])。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
#define ll long long
#define SZ(x) ((int)(x).size())
#define ALL(v) (v).begin(), (v).end()
#define foreach(i, v) for (__typeof((v).begin()) i = (v).begin(); i != (v).end(); ++ i)
#define reveach(i, v) for (__typeof((v).rbegin()) i = (v).rbegin(); i != (v).rend(); ++ i)
#define REP(i,a,n) for ( int i=a; i<int(n); i++ )
#define FOR(i,a,n) for ( int i=a; i< int(n); i—- )
#define lson rt<<1, L, m
#define rson rt<<1|1, m, R
typedef pair<int, int> pii;
typedef pair<int, int> pll;
#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define fi first
#define se second
const int maxn = 1e3 + 7;
const int INF = 0x3f3f3f3f;
int n, m;
ll g[maxn][maxn];
ll dp[maxn][maxn];
ll solve(){
dp[0][0] = 0;
REP(i, 0, n){
REP(j, 0, m){
if((i + j + 1) & 1){
dp[i+1][j] = min(dp[i+1][j], dp[i][j] + g[i][j] * g[i+1][j]);
dp[i][j+1] = min(dp[i][j+1], dp[i][j] + g[i][j] * g[i][j+1]);
}
else{
dp[i+1][j] = min(dp[i+1][j], dp[i][j]);
dp[i][j+1] = min(dp[i][j+1], dp[i][j]);
}
}
}
return dp[n-1][m-1];
}
int main(){
#ifdef ac
freopen("in.txt","r",stdin);
#endif
//freopen("out.txt","w",stdout);
while(~scanf("%d%d", &n, &m)){
memset(dp, INF, sizeof(dp));
REP(i, 0, n) REP(j, 0, m) scanf("%lld", &g[i][j]);
printf("%lld\n", solve());
}
return 0;
}