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.
题目的意思是,有一个矩阵里面有数字.
要从左上角走到右下角.每次只能往右或者往下走一格.
要求一条路径,使得这条路径上数字的乘积 末尾的0最少.
这种一看就是dp的题目.思路如下.
1.dp找到一条2最少的路径, 2的个数为a
2.dp找到一条5最少的路径, 5的个数为b
3.min(a,b)即为答案
trick在于可能输入的数字中有0.考虑一下就好.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <stack>
#include <map>
using namespace std;
int mat[1005][1005];
char direct[1005][1005][2];
int dp[1005][1005][2];
char path[2010];
int path_len;
int factors(int num, int base) {
int ret = 0;
int fct = base;
if (num == 0) return 1;
while (num % fct == 0) {
ret++;
fct *= base;
}
return ret;
}
int mi(int a, int b) {
return a < b ? a : b;
}
int main() {
int n;
scanf("%d", &n);
bool zero = false;
int zero_i;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &mat[i][j]);
if (mat[i][j] == 0) {
zero = true;
zero_i = i;
}
dp[i][j][0]= factors(mat[i][j], 2);
dp[i][j][1] = factors(mat[i][j], 5);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < 2; k++) {
if (i == 0 && j == 0) continue;
if (i == 0) {
dp[i][j][k] += dp[i][j-1][k];
direct[i][j][k] = 'R';
} else if (j == 0) {
dp[i][j][k] += dp[i-1][j][k];
direct[i][j][k] = 'D';
} else {
dp[i][j][k] += dp[i-1][j][k] < dp[i][j-1][k] ? dp[i-1][j][k] : dp[i][j-1][k];
direct[i][j][k] = dp[i-1][j][k] < dp[i][j-1][k] ? 'D' : 'R';
}
}
}
}
if (mi(dp[n-1][n-1][0], dp[n-1][n-1][1]) > 1 && zero) {
printf("1\n");
for (int i = 0; i < zero_i; i++) printf("D");
for (int i = 0; i < n-1; i++) printf("R");
for (int i = zero_i; i < n-1; i++) printf("D");
} else {
printf("%d\n", mi(dp[n-1][n-1][0], dp[n-1][n-1][1]));
path_len = 0;
int k = 1;
if (dp[n-1][n-1][0] < dp[n-1][n-1][1]) k = 0;
for (int i = n-1, j = n-1; i!=0||j!=0; ) {
path[path_len++] = direct[i][j][k];
if (direct[i][j][k] == 'D') {
i--;
} else if (direct[i][j][k] == 'R') {
j--;
}
}
for (int i = 2 * (n - 1) - 1; i >= 0; i--) printf("%c", path[i]);
}
printf("\n");
return 0;
}