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.
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).
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
3 1 2 3 4 5 6 7 8 9
0 DDRR
题意:给你一个n<1000的矩阵,让你走到(n,n),乘起沿途经过的权值,最后的答案最少有几个零,并输出路径
思路:可以先思考0是由2*5得来的,那么我们分别计算一下每个格子2和5的个数,然后DP一下最后一个格子最少有几个2,最少有几个5,去其中最小值就是答案。这里要注意途中有0这种情况,有0的时候答案最多有1个0,但是也有可能是根本没有0,还有要注意的是如果(1,1)或者(n,n)是0,那么结果一定是0。然而codeforces没有判断这种情况的数据。
#include<bits/stdc++.h>
#define INF 0x3fffffff
using namespace std;
int a2[1005][1005];
int dp2[1005][1005];
int re2[1005][1005];//!! 1 UP 0 left
int a5[1005][1005];
int dp5[1005][1005];
int re5[1005][1005];
void dfs(int k[1005][1005], int i, int j){
if(i == 1 && j == 1)return;
if(k[i][j] == 1){
dfs(k,i-1,j);
printf("D");
}
else{
dfs(k,i,j-1);
printf("R");
}
}
int main(){
int n,temp;
int thei,thej;
scanf("%d",&n);
int flag = 1;
int flag2 = 0;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
scanf("%d",&temp);
if(i==1 && j==1 && temp ==0 || i == n && j == n && temp == 0)flag2 = 1;
if(temp == 0){
flag = 0;
thei = i;
thej = j;
}
int tt = temp;
while(tt&&tt%5==0){
tt/=5;
a5[i][j]++;
}
while(temp && temp%2==0){
temp/=2;
a2[i][j]++;
}
}
}
for(int i = 1; i <= n; i++){
dp2[0][i] = INF;
dp2[i][0] = INF;
dp5[i][0] = INF;
dp5[0][i] = INF;
}
dp2[1][1] = a2[1][1];
dp5[1][1] = a5[1][1];
for(int i =1 ; i <= n; i++)
for(int j = 1; j <= n; j++){
if(i==1 && j==1)continue;
if(dp2[i-1][j] > dp2[i][j-1]){
dp2[i][j] = dp2[i][j-1] + a2[i][j];
re2[i][j] = 0;
}
else{
dp2[i][j] = dp2[i-1][j] + a2[i][j];
re2[i][j] = 1;
}
if(dp5[i-1][j] > dp5[i][j-1]){
dp5[i][j] = dp5[i][j-1] + a5[i][j];
re5[i][j] = 0;
}
else{
dp5[i][j] = dp5[i-1][j] + a5[i][j];
re5[i][j] = 1;
}
}
if(!flag && (min(dp2[n][n],dp5[n][n]) >= 1 || flag2) ){
printf("1\n");
for(int i = 1; i <= thei-1; i++)
printf("D");
for(int i = 1; i <= thej-1; i++)
printf("R");
for(int i = thei; i <= n-1; i++)
printf("D");
for(int i = thej; i <= n-1; i++)
printf("R");
printf("\n");
return 0;
}
if(dp2[n][n] < dp5[n][n]){
printf("%d\n",dp2[n][n]);
dfs(re2,n,n);
}
else{
printf("%d\n",dp5[n][n]);
dfs(re5,n,n);
}
printf("\n");
}