Description
Given an n*n grid with non-negative integers, you start from the upper left corner (1,1) and can only move right or down.
Your task is to find the best route to the lower right corner (n,n) without reaching the grid marked with 0.
The best route is when you multiply all the integers you reach on the route, the number of trailing zeros of the product is minimized.
Input
First line with an integer n.
Then n lines, each line with n integers. The numbers in the grid are <= 1,000,000.
The data guarantee that there is at least one legal route.
Output
One line with an integer indicating the answer.
Sample Input
4 1 3 0 0 0 8 2 25 6 5 0 3 0 15 7 4
Sample Output
2
Solution
1 #include <cstdlib> 2 #include <cstdio> 3 #include <vector> 4 #include <climits> 5 using namespace std; 6 #define min(a, b) (a<b?a:b) 7 #define INF 0x3f3f3f3f 8 9 int get2(int a) { 10 int cnt = 0; 11 while (a % 2 == 0) { 12 cnt++; 13 a >>= 1; 14 } 15 return cnt; 16 } 17 18 19 int get5(int a) { 20 int cnt = 0; 21 while (a % 5 == 0) { 22 cnt++; 23 a /= 5; 24 } 25 return cnt; 26 } 27 28 void calc(vector<vector<int> > &grid, vector<vector<int> > &cc2, vector<vector<int> > &cc5) { 29 int N = grid.size(); 30 for (int i = 0; i < N; ++i) { 31 for (int j = 0; j < N; ++j) { 32 if (grid[i][j]) { 33 cc2[i][j] = get2(grid[i][j]); 34 cc5[i][j] = get5(grid[i][j]); 35 } 36 else { 37 cc2[i][j] = INF; 38 cc5[i][j] = INF; 39 } 40 } 41 } 42 } 43 44 int main() { 45 int N; 46 scanf("%d", &N); 47 vector<vector<int> > grid(N, vector<int>(N, 0)); 48 vector<vector<int> > cc2(N, vector<int>(N, 0)); 49 vector<vector<int> > cc5(N, vector<int>(N, 0)); 50 vector<vector<int> > dp2(N+1, vector<int>(N+1, INF)); 51 vector<vector<int> > dp5(N + 1, vector<int>(N + 1, INF)); 52 for (int i = 0; i < N; ++i) { 53 for (int j = 0; j < N; ++j) { 54 int v; 55 scanf("%d", &v); 56 grid[i][j] = v; 57 } 58 } 59 calc(grid, cc2, cc5); 60 dp2[1][1] = cc2[0][0]; 61 for (int i = 1; i <= N; ++i) { 62 for (int j = 1; j <= N; ++j) { 63 dp2[i][j] = min(dp2[i][j], min(dp2[i - 1][j], dp2[i][j - 1]) + cc2[i-1][j-1]); 64 } 65 } 66 67 int ans = dp2[N][N]; 68 69 dp5[1][1] = cc5[0][0]; 70 for (int i = 1; i <= N; ++i) { 71 for (int j = 1; j <= N; ++j) { 72 dp5[i][j] = min(dp5[i][j], min(dp5[i - 1][j], dp5[i][j - 1]) + cc5[i - 1][j - 1]); 73 } 74 } 75 76 ans = min(dp2[N][N], dp5[N][N]); 77 78 printf("%d\n", ans); 79 }