您的位置:首页 > 其它

hihocoder1241 : Best Route in a Grid

2015-10-12 10:09 295 查看

题目链接:

传送门

题意:

给定一个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

;
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

));
}
return 0;
}
/***
3
2 5 2
2 5 2
2 5 2
5
5 5 5 2 2
5 5 5 2 2
5 5 5 2 2
5 5 5 2 2
5 5 5 2 2
****/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hihocoder