CodeForces2B The least round way

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.

Example

Input
3
1 2 3
4 5 6
7 8 9
Output
0
DDRR

给出n,再给出一个n*n的矩阵,你从左上角出发到右下角,只能向右和向下移动,将你途中遇到所有数字相乘,使得到的乘积数字末尾的0的数量最少,因此,我们只需要对数列中的
0,2,5进行分析即可。
tip1.出现0时。可以使答案强制为1,在答案大于1时,应穿过0所在位置。
tip2.每一对2和5都会使答案的0增加一个,所以只要使2的数量或者5的数量最少即可。
对于tip1,只要记录任意一个0的位置,并判断是否最优解。
对于tip2,从终点开始逆推a[i][j]+=min(a[i-1][j],a[i][j-1]),得出可以解决所有问题的子问题。
代码及注释如下:
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
int f[1001][1001][2],n,x,k;
char g[1001][1001][2];

void move(int x,int y)
{
    if(x==1&&y==1)
    return ;
    if(g[x][y][k])
    move(x-1,y),putchar('D');
    else
    move(x,y-1),putchar('R');
}

int main()
{
    scanf("%d",&n);
    memset(f,0,sizeof(f));
    for(int i=2;i<=n;++i)
        f[0][i][0]=f[0][i][1]=f[i][0][0]=f[i][0][1]=inf;    //定义边界 
    for(int i=1;i<=n;++i)
    {
        for(int j=1;j<=n;++j)
        {
            scanf("%d",&k);
            if(!k)
                x=i;        //x记录0出现地址 
            else
            {
                while(k%2==0) ++f[i][j][0],k/=2;    //2的倍数 
                while(k%5==0) ++f[i][j][1],k/=5;    //5的倍数 
            }
            for(int k=0;k<2;k++)
            {
                if(g[i][j][k]=f[i-1][j][k]<f[i][j-1][k])    //上方和左方分别比较2和5的数量 ,选择更少的 
                    f[i][j][k]+=f[i-1][j][k];
                else
                    f[i][j][k]+=f[i][j-1][k];
            }
        }
    }
    k=f[n][n][1]<f[n][n][0];    //2和5哪个更少,k=0代表2更少并选择2,k=1代表5更少并选择5 
    if(x&&f[n][n][k]>1)
    {
        cout<<"1\n";        //选择通过0的情况 
        for(int i=2;i<=x;i++)
        putchar('D');
        for(int i=2;i<=n;i++)
        putchar('R');
        for(int i=x+1;i<=n;i++)
        putchar('D');
        puts("");
    }
    else
    {
        printf("%d\n",f[n][n][k]),        //未经过0时,2和5的最小值决定0的数量 
        move(n,n);
        puts("");
    }
}

 

转载于:https://www.cnblogs.com/qq936584671/p/6828089.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值