B. The least round way
time limit per test2 seconds
memory limit per test64 megabytes
inputstandard input
outputstandard output
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.
Input
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).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Examples
input
3
1 2 3
4 5 6
7 8 9
output
0
DDRR
题意大概就是要从左上角走到右下角,要求走的路所得乘积0最少,而要想乘积里面有0,则数字中就要有因子2或5,所有问题就转化为所走路径中保证因子2或5的数量最少。
这个是一个简单的dp,最后递归输出路径即可。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<stack>
#include<iostream>
#include<algorithm>
const int maxn=1e3+10;
const int INF=0x3f3f3f3f;
using namespace std;
int dp[2][maxn][maxn];
void go(int x,int y,int factor){
if(x==1&&y==1) return;
if(dp[factor][x-1][y]<dp[factor][x][y-1]) go(x-1,y,factor),printf("D");
else go(x,y-1,factor),printf("R");
}
int main(){
int n,a,x,y;
int u,v;
int flag = 0;
cin>>n;
memset(dp,60,sizeof(dp));
dp[1][0][1] = dp[0][0][1] = 0;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
u=v=0;
scanf("%d",&a);
if(!a){
x = i,y = j;
flag = 1;
}
while(a%2==0&&a){
u++;
a/=2;
}
while(a%5==0&&a){
v++;
a/=5;
}
dp[0][i][j] = min(dp[0][i-1][j],dp[0][i][j-1])+u;
dp[1][i][j] = min(dp[1][i-1][j],dp[1][i][j-1])+v;
}
}
int ans = min(dp[1][n][n],dp[0][n][n]);
if(ans>1&&flag){
cout<<1<<endl;
for(int i=1;i<x;i++){
printf("D");
}
for(int i=1;i<y;i++){
printf("R");
}
for(int i=x;i<n;i++){
printf("D");
}
for(int j=y;j<n;j++){
printf("R");
}
return 0;
}
cout<<ans<<endl;
if(ans==dp[0][n][n]){
go(n,n,0);
}
else{
go(n,n,1);
}
}