1. 程式人生 > >code force 2B The least round way

code force 2B The least round way

long ddr result start sam there num 是否 最小值

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("");
    }
}

code force 2B The least round way