思路:两次dp分别求2,5出现的幂的一条路径,如果这条路径上有0,那么最后的结果肯定是1(1个0),不然就是只出现2或5的情况;不然就是2和5出现的最小的那种情况。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iostream>
#define maxn 1010
#define inf 0xfffffff
using namespace std;
int tmp[maxn][maxn],five[maxn][maxn],two[maxn][maxn];
int dp2[maxn][maxn],dp5[maxn][maxn];
char dir2[maxn][maxn],dir5[maxn][maxn];
int n;
int get(int p,int n)
{
if(n==0)
return 1;
int cnt=0;
while(n%p==0)
{
n/=p;
cnt++;
}
return cnt;
}
int zero_x,zero_y;
bool flag;
void print(char dir[][maxn],int x,int y)
{
//cout<<x<<":"<<y<<endl;
if(x==1&&y==1)
return ;
if(dir[x][y]=='D')
print(dir,x-1,y);
else
print(dir,x,y-1);
printf("%c",dir[x][y]);
}
int main()
{
scanf("%d",&n);
flag=true;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
scanf("%d",&tmp[i][j]);
if(tmp[i][j])
{
two[i][j]=get(2,tmp[i][j]);
five[i][j]=get(5,tmp[i][j]);
}
else
{
flag=false;
zero_x=i;
zero_y=j;
}
}
memset(dp2,0,sizeof(dp2));
memset(dp5,0,sizeof(dp5));
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(tmp[i][j]==0)
{
dp2[i][j]=inf;
}
else if(i==1&&j==1)
{
dir2[i][j]=' ';
dp2[i][j]=two[i][j];
}
else if(i==1)
{
dp2[i][j]=dp2[i][j-1]+two[i][j];
dir2[i][j]='R';
}
else if(j==1)
{
dp2[i][j]=dp2[i-1][j]+two[i][j];
dir2[i][j]='D';
}
else
{
if(dp2[i-1][j]<dp2[i][j-1])
dir2[i][j]='D';
else
dir2[i][j]='R';
dp2[i][j]=min(dp2[i-1][j],dp2[i][j-1])+two[i][j];
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(tmp[i][j]==0)
{
dp5[i][j]=inf;
}
else if(i==1&&j==1)
{
dir5[i][j]=' ';
dp5[i][j]=five[i][j];
}
else if(j==1)
{
dir5[i][j]='D';
dp5[i][j]=dp5[i-1][j]+five[i][j];
}
else if(i==1)
{
dir5[i][j]='R';
dp5[i][j]=dp5[i][j-1]+five[i][j];
}
else
{
if(dp5[i-1][j]<dp5[i][j-1])
dir5[i][j]='D';
else
dir5[i][j]='R';
dp5[i][j]=min(dp5[i-1][j],dp5[i][j-1])+five[i][j];
}
}
if(!flag)
{
if(dp2[n][n]==0)
{
printf("0\n");
print(dir2,n,n);
}
else if(dp5[n][n]==0)
{
printf("0\n");
print(dir5,n,n);
}
else
{
printf("1\n");
for(int i=2;i<=zero_x;i++)
printf("D");
for(int j=2;j<=zero_y;j++)
printf("R");
for(int i=zero_x+1;i<=n;i++)
printf("D");
for(int j=zero_y+1;j<=n;j++)
printf("R");
}
}
else
{
if(dp2[n][n]>dp5[n][n])
{
printf("%d\n",dp5[n][n]);
print(dir5,n,n);
}
else
{
printf("%d\n",dp2[n][n]);
print(dir2,n,n);
}
}
printf("\n");
return 0;
}