Description
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 exceeding109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Sample Input
3
1 2 3
4 5 6
7 8 9
0
DDRR
题目大意:
给出一个n × n的矩阵,从矩阵的左上角到矩阵的右下角,寻找一条路径,使得该路径上各数的乘积结果中数字0的个数最少。
解题思路:
乘积出现0,最小的是2×5,而其他的出现0的数也是多个2和5的乘积,因此只需找出一条路径中2和5中的个数最少的,则最少的2或最少的5的个数即是0的个数,但是注意特殊情况,当路径中有0时,无论2和5的个数怎么样,乘积的结果只有一个0,而路径只需任意一条经过数0的即可。
代码如下:
#include <iostream>
#include <cstdio>
#define N 1005
using namespace std;
int n,zx,zy,g[2][N][N],dp[2][N][N],mat[2][N][N];
char path[4*N];
int solve(int mk)
{
int i,j;
g[mk][1][1] = 0;
dp[mk][1][1] = mat[mk][1][1];
for(i = 1; i <= n; ++i)
{
for(j = 1; j <= n; ++j)
{
if(i == 1 && j == 1)
continue;
if(i == 1)
{
dp[mk][i][j] = dp[mk][i][j - 1] + mat[mk][i][j];
g[mk][i][j] = 1;
}
else if (j == 1)
{
dp[mk][i][j] = dp[mk][i - 1][j] + mat[mk][i][j];
g[mk][i][j] = 0;
}
else
{
int tp1 = dp[mk][i - 1][j];
int tp2 = dp[mk][i][j - 1];
if (tp1 < tp2)
{
dp[mk][i][j] = dp[mk][i - 1][j] + mat[mk][i][j];
g[mk][i][j] = 0;
}
else
{
dp[mk][i][j] = dp[mk][i][j - 1] + mat[mk][i][j];
g[mk][i][j] = 1;
}
}
}
}
return dp[mk][n][n];
}
void Path(int mk,int x,int y)
{
if(x == 1 && y == 1)
return ;
else if(g[mk][x][y] == 0)
{
Path(mk,x - 1,y);
printf("D");
}
else
{
Path(mk,x,y - 1);
printf("R");
}
}
int main()
{
int i,j,x,tmp,ans,ans1,ans2,mk,flag = 0;
scanf("%d",&n);
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
mat[0][i][j] = mat[1][i][j] = 0;
scanf("%d",&x);
if (x == 0)
{
zx = i;
zy = j;
flag = 1;
continue;
}
tmp = x;
while(tmp % 2 == 0)
{
mat[0][i][j]++;
tmp /= 2;
}
tmp = x;
while (tmp % 5 == 0)
{
mat[1][i][j]++;
tmp /= 5;
}
}
}
ans1 = solve(0);
ans2 = solve(1);
if(ans1 < ans2)
{
ans = ans1;
mk = 0;
}
else
{
ans = ans2;
mk = 1;
}
if(flag && ans > 1)
{
printf("1\n");
for(i = 2; i <= zx; i++)
printf("D");
for(i = 2; i <= n; i++)
printf("R");
for(i = zx + 1; i <= n; i++)
printf("D");
printf("\n");
}
else
{
printf("%d\n",ans);
Path(mk,n,n);
printf("\n");
}
return 0;
}