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 exceeding
1
0
9
10^9
109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
0
DDRR
Solution
给一个矩阵,让你从左上角走到右下角,每走到一个位置则需要乘上该位置的元素,问最终的值最少有多少个末尾0
元素中没有0:
一个数的0的个数 = min(cnt2, cnt5) ,其中cnt2 = 因子2的个数,cnt5 = 因子5的个数
所以最终答案只看这两个因子个数的最小值,故我们可以分开dp,分别算出最少的2和最少的5的情况并记录路径
最终答案就是二者的最小值
若元素中有0:
0会导致最终答案
<
=
1
<=1
<=1,我们把0当作10来算贡献:
若最终答案 > 1,说明一定可以选一条路过0的路径,并使得答案为1
若最终答案 = 1,说明最优答案之一可能绕过了0,实际值为1,或者没绕过0, 实际值为0
若最终答案 = 0,说明最优答案之一肯定绕过了0
后两种情况不需要做特别处理,同无0的情况一样处理即可
Code
int a[maxn][maxn];
pii cal(int x){
int num2 = 0, num5 = 0;
//把0当做10
if(x == 0) return mpp(1,1);
while(x % 2 == 0) num2++, x /= 2;
while(x % 5 == 0) num5++, x /= 5;
return mpp(num2,num5);
}
int n;
int dp[maxn][maxn][2];
int path[maxn][maxn][2];//up 1 left 0
int cnt[maxn][maxn][2];
void dfs(int x,int y,int op){
if(x == 1 && y == 1) return ;
if(path[x][y][op] == 1) {
dfs(x-1,y,op);
printf("D");
}
if(path[x][y][op] == 0){
dfs(x,y-1,op);
printf("R");
}
}
void get_path(int op){
dfs(n,n,op);
}
void solve(int op){
for(int i = 2;i <= n;++i){
for(int j = 2;j <= n;++j){
dp[i][j][op] = min(dp[i-1][j][op], dp[i][j-1][op]) + cnt[i][j][op];
if(dp[i][j][op] == dp[i-1][j][op] + cnt[i][j][op]) path[i][j][op] = 1;
else path[i][j][op] = 0;
}
}
}
int main() {
scanf("%d",&n);
clr(path,-1);
int stx = 0, sty = 0;
for(int i = 1;i <= n;++i)
for(int j = 1;j <= n;++j) {
scanf("%d",&a[i][j]);
if(a[i][j] == 0) stx = i, sty = j;
cnt[i][j][0] = cal(a[i][j]).fi;
cnt[i][j][1] = cal(a[i][j]).se;
}
dp[1][1][0] = cal(a[1][1]).fi , dp[1][1][1] = cal(a[1][1]).se;
for(int j = 2;j <= n;++j) {
path[1][j][0] = path[1][j][1] = 0;
dp[1][j][0] = dp[1][j-1][0] + cal(a[1][j]).fi;
dp[1][j][1] = dp[1][j-1][1] + cal(a[1][j]).se;
}
for(int i = 2;i <= n;++i){
path[i][1][0] = path[i][1][1] = 1;
dp[i][1][0] = dp[i-1][1][0] + cal(a[i][1]).fi;
dp[i][1][1] = dp[i-1][1][1] + cal(a[i][1]).se;
}
solve(0);solve(1);
int res = min(dp[n][n][0], dp[n][n][1]);
if(res > 1 && stx) {
printf("1\n");
for(int i = 1;i < stx;++i) printf("D");
for(int i = 1;i < sty;++i) printf("R");
for(int i = 1;i <= n - sty;++i) printf("R");
for(int i = 1;i <= n - stx;++i) printf("D");
printf("\n");
} else{
printf("%d\n", res);
if(res == dp[n][n][0]) get_path(0);
else get_path(1);
}
return 0;
}