There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
- starts in the upper left cell of the matrix;
- each following cell is to the right or down from the current cell;
- the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least “round”. In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
解析:dp还是比较简单的,就是有个坑点,输入数字可能有0,则在最小路径的数>0时,则肯定是经过0的最优。
#include <iostream>
#include <cstring>
#define INF 0xFFFFFF
using namespace std;
int A[1005][1005];
int two[1005][1005];
int five[1005][1005];
char ctwo[1005][1005];
char cfive[1005][1005];
int fact(int n, int factor)
{
int s=0;
if (n==0)
return 1;
while (n%factor==0){
n=n/factor;
s++;
}
return s;
}
void p(char q[][1005],int i,int j)
{
if (!q[i][j])
return;
if (q[i][j]=='R')
p(q,i,j-1);
else p(q,i-1,j);
cout << q[i][j];
return ;
}
int main()
{
memset(A,0,sizeof(A));
memset(two,0,sizeof(two));
memset(five,0,sizeof(five));
int n,t,f;
int nozero = 1, zeroi;
cin >> n;
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++){
cin >> A[i][j];
if (A[i][j] == 0)
nozero = 0, zeroi = i;
t=fact(A[i][j],2),f=fact(A[i][j],5);
if (i==1 && j==1)
two[1][1] = t,
five[1][1] = f,
ctwo[i][j] = 0, cfive[i][j] = 0;
else if (i==1)
two[1][j] = t + two[1][j-1],
five[1][j] = f + five[1][j-1],
ctwo[i][j] = 'R',cfive[i][j] = 'R';
else if (j==1)
two[i][1] = t + two[i-1][1],
five[i][1] = f + five[i-1][1],
ctwo[i][j] = 'D', cfive[i][j] = 'D';
else{
two[i][j] = min(two[i-1][j],two[i][j-1]) + t;
if (two[i-1][j]>two[i][j-1])
ctwo[i][j] = 'R';
else
ctwo[i][j] = 'D';
five[i][j] = min(five[i-1][j],five[i][j-1]) + f;
if (five[i-1][j]>five[i][j-1])
cfive[i][j] = 'R';
else
cfive[i][j] = 'D';
}
}
int ans = min(two[n][n],five[n][n]);
if (nozero || ans==0){
cout << ans << endl;
if (two[n][n]>five[n][n])
p(cfive,n,n);
else p(ctwo,n,n);
}
else{
cout << 1 << endl;
for (int i=1;i<zeroi;i++) cout << "D";
for (int i=1;i<n;i++) cout << "R";
for (int i=zeroi;i<n;i++) cout << "D";
}
return 0;
}