1. 程式人生 > 其它 >Codeforces 2 B. The least round way

Codeforces 2 B. The least round way

題意:

二維陣列中都是非負整數,從[1,1]走到[n,n]每次可以向右或向下走,求路徑上數乘積的0最少是多少,並輸出路徑。

提示:

最少0就是最少因子2或者最少因子5,分別dp一下。

注意:

如果路徑裡有0,那麼相乘後0的個數一定是1。

C#10 .net6 程式碼

using System.Text;

int n = int.Parse(Console.ReadLine()!);
int[,,] dp = new int[n, n, 2];
char[,,] vis = new char[n, n, 2];
int zx = -1;
int zy = -1;

int GetCnt(int x, int
b) { if (x == 0) { return 1; } int cnt = 0; while (x != 0 && (x % b == 0)) { cnt++; x /= b; } return cnt; } for (int i = 0; i < n; i++) { var line = Console.ReadLine()!.Split(' '); for (int j = 0; j < n; j++) { int x = int
.Parse(line[j]); if (x == 0) { zx = i; zy = j; } int cnt2 = GetCnt(x, 2); int cnt5 = GetCnt(x, 5); if (i == 0 && j == 0) { dp[i, j, 0] = cnt2; dp[i, j, 1] = cnt5; } else if (i == 0
&& j > 0) { vis[i, j, 0] = 'R'; vis[i, j, 1] = 'R'; dp[i, j, 0] = dp[i, j - 1, 0] + cnt2; dp[i, j, 1] = dp[i, j - 1, 1] + cnt5; } else if (i > 0 && j == 0) { vis[i, j, 0] = 'D'; vis[i, j, 1] = 'D'; dp[i, j, 0] = dp[i - 1, j, 0] + cnt2; dp[i, j, 1] = dp[i - 1, j, 1] + cnt5; } else { if (dp[i, j - 1, 0] < dp[i - 1, j, 0]) { vis[i, j, 0] = 'R'; dp[i, j, 0] = dp[i, j - 1, 0] + cnt2; } else { vis[i, j, 0] = 'D'; dp[i, j, 0] = dp[i - 1, j, 0] + cnt2; } if (dp[i, j - 1, 1] < dp[i - 1, j, 1]) { vis[i, j, 1] = 'R'; dp[i, j, 1] = dp[i, j - 1, 1] + cnt5; } else { vis[i, j, 1] = 'D'; dp[i, j, 1] = dp[i - 1, j, 1] + cnt5; } } } } int ans = Math.Min(dp[n - 1, n - 1, 0], dp[n - 1, n - 1, 1]); string Gao(int x, int y, int type) { if (x == 0 && y == 0) { return ""; } if (vis[x, y, type] == 'R') { return Gao(x, y - 1, type) + 'R'; } else { return Gao(x - 1, y, type) + 'D'; } } if (ans >= 1 && zx != -1) { Console.WriteLine(1); StringBuilder sb = new(); for (int i = 0; i < zx; i++) { sb.Append('D'); } for (int j = 0; j < zy; j++) { sb.Append('R'); } for (int i = zx; i < n - 1; i++) { sb.Append('D'); } for (int j = zy; j < n - 1; j++) { sb.Append('R'); } Console.WriteLine(sb.ToString()); } else { Console.WriteLine(ans); string str = string.Empty; if (dp[n - 1, n - 1, 0] < dp[n - 1, n - 1, 1]) { str = Gao(n - 1, n - 1, 0); } else { str = Gao(n - 1, n - 1, 1); } Console.WriteLine(str); }