首先注意,两个一起考虑的乱搞做法(dp转移中带有复杂的贪心原则)往往是错的,但是我自己很难搞懂为什么错。
分离的思想在数学中常常体现,因此在题目里要优先考虑答案能否由分离的思想导出,若做不到再考虑上面复杂的贪心原则(即放弃治疗)。这里的分离就是说,我们单独考虑优化2,不管5;以及单独考虑优化5,不管2。
设单独优化2的答案为v1
,单独优化5的答案为v2
。如果v1 <= v2
,就选单独优化2的做法;否则选单独优化5的。以v1 <= v2
为例(另一种同理),5的其他路径都是大于等于v2的,包括单独优化2的那条路径,所以单独优化2的路径的答案必然是v1。
特判0:有0的时候最优解不超过1。我的做法是先求不含0的路径,再看最优解是不是小于等于1,这种做法只能说一般般。
官方题解的做法更优秀:用10替代0,于是走过了0的最优路径至少为1。假如替代后的图有一条路径,最优解是0,则说明最优解是0;否则最优解总是可以取(注:等于1时非必须)走过了至少一个0的。
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define rep(i,a,b) for(int i = (a);i <= (b);++i)
#define re_(i,a,b) for(int i = (a);i < (b);++i)
#define dwn(i,a,b) for(int i = (a);i >= (b);--i)
const int N = 1e3 + 5,INF = 1e9;
int n,c[2][N][N],dp[2][N][N];char pre[2][N][N];
void dbg(){puts("");}
template<typename T, typename... R>void dbg(const T &f, const R &... r) {
cout << f << " ";
dbg(r...);
}
template<typename Type>inline void read(Type &xx){
Type f = 1;char ch;xx = 0;
for(ch = getchar();ch < '0' || ch > '9';ch = getchar()) if(ch == '-') f = -1;
for(;ch >= '0' && ch <= '9';ch = getchar()) xx = xx * 10 + ch - '0';
xx *= f;
}
void read(){}
template<typename T,typename ...R>void read(T &x,R &...r){
read(x);
read(r...);
}
bool legal(int x,int y){
return x >= 1 && y >= 1 && c[0][x][y] != -1;
}
int main(int argc, char** argv) {
read(n);
int zerox = -1,zeroy = -1;
rep(i,1,n) rep(j,1,n){
int x;read(x);
if(!x){
c[0][i][j] = c[1][i][j] = -1;
zerox = i;zeroy = j;
continue;
}
while(x % 2 == 0) c[0][i][j]++,x /= 2;
while(x % 5 == 0) c[1][i][j]++,x /= 5;
}
rep(u,0,1) rep(i,1,n) rep(j,1,n) dp[u][i][j] = INF;
rep(u,0,1) dp[u][1][1] = c[u][1][1];
rep(u,0,1) rep(i,1,n) rep(j,1,n){
if(!legal(i,j)) continue;
if(legal(i-1,j) && dp[u][i][j] >= dp[u][i-1][j] + c[u][i][j]){
dp[u][i][j] = dp[u][i-1][j] + c[u][i][j];
pre[u][i][j] = 'D';
}
if(legal(i,j-1) && dp[u][i][j] >= dp[u][i][j-1] + c[u][i][j]){
dp[u][i][j] = dp[u][i][j-1] + c[u][i][j];
pre[u][i][j] = 'R';
}
}
int mn = min(dp[0][n][n],dp[1][n][n]);
if(!(~zerox) || (~zerox && mn <= 1)){
printf("%d\n",mn);
string ans;
for(int u = (mn == dp[1][n][n]),x = n,y = n;x > 1 || y > 1;){
ans += pre[u][x][y];
if(pre[u][x][y] == 'D') --x;
else --y;
}
reverse(ans.begin(),ans.end());
puts(ans.c_str());
}
else{
puts("1");
string ans;
re_(i,0,zerox-1) ans += 'D';
re_(i,0,n-1) ans += 'R';
re_(i,0,n-zerox) ans += 'D';
puts(ans.c_str());
}
return 0;
}