问题链接:http://codeforces.com/contest/2/problem/B
有一个由非负整数构成的 n × n 方阵。你需要在其中找到这样一条路径:
- 从方阵的左上角出发;
- 每次只能向右或向下移动一个方格;
- 最终到达方阵右下角。
此外,如果将路径上经过的所有数字相乘,结果应该是“尽量少”的,也就是说,它应该以可能最小的末尾零数结束。
输入
第一行为一个整数 n(2 ≤ n ≤ 1000),表示矩阵的大小。接下来的 n 行包含矩阵元素(非负整数,不超过 10^9)。
输出
第一行输出最少的末尾零数。第二行输出对应的路径本身。
我想了以下方法:无论最后的答案如何,它都应该包含最小的2和5的幂。因此,我对输入矩阵中的每个条目计算了2和5的幂,并将它们存储在单独的矩阵中。
for (i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
{
cin>>foo;
matrix[i][j] = foo;
int n1 = calctwo(foo); // calculates the number of 2's in factorisation of that number
int n2 = calcfive(foo); // calculates number of 5's
two[i][j] = n1;
five[i][j] = n2;
}
}
接着,我做了这个:
for (i = 0; i < n; i++)
{
for ( j = 0; j < n; j++ )
{
dp[i][j] = min(two[i][j],five[i][j]); // Here, dp[i][j] will store minimum number of 2's and 5's.
}
}
但上述并不是一个有效的答案,我不知道为什么。我实施了正确的方法吗?或者,这是解决这个问题的正确方式吗?
编辑:这里是我的计算数字中二和五的函数。
int calctwo (int foo)
{
int counter = 0;
while (foo%2 == 0)
{
if (foo%2 == 0)
{
counter++;
foo = foo/2;
}
else
break;
}
return counter;
}
int calcfive (int foo)
{
int counter = 0;
while (foo%5 == 0)
{
if (foo%5 == 0)
{
counter++;
foo = foo/5;
}
else
break;
}
return counter;
}
编辑2:给定链接中的I/O示例:
输入:
3
1 2 3
4 5 6
7 8 9
输出:
0
DDRR
1 * 2 * 3 * 6 * 9 = 324
- Tim Biegeleisen