本文主要是介绍Codefoeces 2B. The least round way,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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
题意:找出从矩阵左上角到右下角的一条路径, 使得这条路径上的所有数的乘积末尾0的个数最小
思路:使用dp的方法分别找出两条路径, 第一条路径是因子2出现最少的, 第二条路径是因子5出现最少的, 最后比较因子2的个数和因子5的个数, 选择少的那一条路径
特殊情况: 找出的路径如果大于1个0, 并且矩阵里面有0出现, 则选择经过0的路径
#include <stdio.h>
#include <algorithm>
using namespace std;const int MAXN = 1001;
const int INF = 1 << 30;
char path[MAXN][MAXN][2];
int matrix[1001][1001][2];
int pos = 0;void PrintPath(int x, int y, int Min)
{if(x == 1 && y == 1) return;if(path[x][y][Min]){PrintPath(x - 1, y, Min);putchar('D');}else{PrintPath(x , y - 1, Min);putchar('R');}
}int main()
{
#ifdef _LOCALfreopen("F://input.txt", "r", stdin);
#endifint n;scanf("%d", &n);for(int i = 2; i <= n; ++i)matrix[0][i][0] = matrix[0][i][1] = matrix[i][0][0] = matrix[i][0][1] = INF;//矩阵围起来的边界for(int i = 1; i <= n; ++i){for(int j = 1; j <= n; j++){int key;scanf("%d", &key);if(key == 0)pos = i;else{while(key % 2 == 0){++matrix[i][j][0];key /= 2;}while(key % 5 == 0){++matrix[i][j][1];key /= 5;}}for(int k = 0; k < 2; ++k){path[i][j][k] = matrix[i - 1][j][k] < matrix[i][j - 1][k] ? 1 : 0; matrix[i][j][k] += min(matrix[i - 1][j][k], matrix[i][j - 1][k]);}}}int Min = matrix[n][n][0] < matrix[n][n][1] ? 0 : 1; if(pos && matrix[n][n][Min] > 1){puts("1");for(int i = 2; i <= pos; ++i) putchar('D');for(int i = 2; i <= n ; ++i) putchar('R');for(int i = pos + 1; i <= n; ++i) putchar('D');}else{printf("%d\n", matrix[n][n][Min]);PrintPath(n, n, Min);}return 0;
}
这篇关于Codefoeces 2B. The least round way的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!