hihocoder1241 : Best Route in a Grid

来源:互联网 发布:淘宝丫头正品商城正吗 编辑:程序博客网 时间:2024/05/16 12:54

题目链接:

传送门

题意:

给定一个n*n的矩阵,每次只能往下或者往左走,而且0的位置不能走,求最后走的格子的数的乘积末尾连续0的最小个数。

分析:

很明显最后末尾连续0的个数和素因子2和素因子5的数量有关。那么我们就做两次dp,设dp[i][j]表示走的(i,j)的时候素因子2/5的最小的个数。然后那就是一个简单的dp了。

Code:

#include <bits/stdc++.h>using namespace std;const int maxn = 1e3+10;int a[maxn][maxn];int dp[maxn][maxn];int cnt1[maxn][maxn];int cnt2[maxn][maxn];const int inf = 1000000;int fen(int x,int f) {    int num = 0;    while(x%f==0) {        num++;        x=x/f;    }    return num;}void debug() {    cout<<"======================"<<endl;    for(int i=0; i<=n; i++) {        for(int j=0; j<=n; j++) {            cout<<dp[i][j]<<" ";        }        cout<<endl;    }    cout<<"======================"<<endl;}int main() {    int n;    while(~scanf("%d",&n)) {        for(int i=1; i<=n; i++) {            for(int j=1; j<=n; j++)                scanf("%d",&a[i][j]);        }        memset(cnt1,0,sizeof(cnt1));        memset(cnt2,0,sizeof(cnt2));        for(int i=1; i<=n; i++) {            for(int j=1; j<=n; j++) {                if(!a[i][j]) {                    cnt1[i][j]=inf;                    cnt2[i][j]=inf;                } else {                    cnt1[i][j]=fen(a[i][j],2);                    cnt2[i][j]=fen(a[i][j],5);                }            }        }        for(int i=0; i<=n; i++)            dp[i][0]=dp[0][i]=inf;        dp[1][0]=0,dp[0][1]=0;        for(int i=1; i<=n; i++) {            for(int j=1; j<=n; j++) {                dp[i][j]=min(dp[i][j-1],dp[i-1][j])+cnt1[i][j];            }        }        int tmp = dp[n][n];        for(int i=0; i<=n; i++)            dp[i][0]=dp[0][i]=inf;        dp[1][0]=dp[0][1]=0;        for(int i=1; i<=n; i++) {            for(int j=1; j<=n; j++) {                dp[i][j]=min(dp[i][j-1],dp[i-1][j])+cnt2[i][j];            }        }        printf("%d\n",min(tmp,dp[n][n]));    }    return 0;}/***32 5 22 5 22 5 255 5 5 2 25 5 5 2 25 5 5 2 25 5 5 2 25 5 5 2 2****/
1 0
原创粉丝点击