zoukankan      html  css  js  c++  java
  • matrix(dp)

    matrix

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

    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 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 3 1 2 3 2 2 1 2 3 2 2 1 1 2 4
     
    Sample Output
    4 8
     
    Source
     

    题解:dp题,发现自己对于dp太弱了。。。

    题意是一个n*m的矩阵,从(1,1)走到(n,m)的a1*a2+a3*a4+a5*a6。。。。其中a1,a2。。。是矩阵的当前值;

    由于只能向右向下,从(1,1)开始,那么(x+1,y)或(x,y+1)由于是从1+1=2偶数开始,所以到x+y+1是奇数的时候再进行运算,

    所以每次往前推两步即可,初始化dp为INF,因为求最小值,dp[1][1]=0;状态转移方程:

    if((i+j)&1){
        dp[i][j]=min(dp[i-1][j]+num[i-1][j]*num[i][j],dp[i][j-1]+num[i][j-1]*num[i][j]);
       }
       else dp[i][j]=min(dp[i-1][j],dp[i][j-1]);

    代码:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    #define mem(x,y) memset(x,y,sizeof(x))
    using namespace std;
    const int INF=0x3f3f3f3f;
    const double PI=acos(-1.0);
    const int MAXN=1010;
    int dp[MAXN][MAXN],num[MAXN][MAXN];
    int main(){
    	int n,m;
    	while(~scanf("%d%d",&n,&m)){
    		mem(dp,INF);
    		for(int i=1;i<=n;i++)
    		for(int j=1;j<=m;j++){
    			scanf("%d",&num[i][j]);
    			if(i==1&&j==1){
    				dp[i][j]=0;continue;
    			}
    			if((i+j)&1){
    				dp[i][j]=min(dp[i-1][j]+num[i-1][j]*num[i][j],dp[i][j-1]+num[i][j-1]*num[i][j]);
    			}
    			else dp[i][j]=min(dp[i-1][j],dp[i][j-1]);
    		}
    		printf("%d
    ",dp[n][m]);
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    Amphiphilic Carbon Molecules [UVA
    2018宁夏邀请赛I题 bubble sort(思维题
    CF1198E Rectangle Painting 2(最小割 思维
    Problem : 这个题如果不是签到题 Asm.Def就女装(积性函数dp
    cogs2223. [SDOI2016 Round1] 生成魔咒(后缀数组 hash 二分 set
    cogs1709. [SPOJ 705] 不同的子串(后缀数组
    cogs249 最长公共子串(后缀数组 二分答案
    hdu2222 Keywords Search (AC自动机板子
    ccpc网赛 hdu6703 array(权值线段树
    ccpc网赛 hdu6705 path(队列模拟 贪心
  • 原文地址:https://www.cnblogs.com/handsomecui/p/4984909.html
Copyright © 2011-2022 走看看