CodeForces 2B The least round way (DP+打印路径)

题目链接:codeforces.com/problemset/problem/2/B

#include<bits/stdc++.h>
using namespace std;

#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long

#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))

#define pii pair<ll,ll>
#define mk(x,y) make_pair(x,y)
#define fi first
#define se second

const int  maxn =1e3+5;
const int mod=1e9+7;
const int ub=1e6;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}

int n,x;
int mp2[maxn][maxn],mp5[maxn][maxn];
int dp2[maxn][maxn],dp5[maxn][maxn];
int mp0[maxn][maxn],dp0[maxn][maxn];

void output2(int x,int y){
    if(x==1&&y==1) return ;
    if(dp2[x][y]==dp2[x-1][y]+mp2[x][y]){
        output2(x-1,y);
        printf("D");
    }
    else{
        output2(x,y-1);
        printf("R");
    }
}

void output5(int x,int y){
    if(x==1&&y==1) return ;
    if(dp5[x][y]==dp5[x-1][y]+mp5[x][y]){
        output5(x-1,y);
        printf("D");
    }
    else{
        output5(x,y-1);
        printf("R");
    }
}

void output0(int x,int y){
    if(mp0[x][y]){
        rep(i,1,x) printf("D");
        rep(i,1,y) printf("R");
        return ;
    }
    if(dp0[x-1][y]){
        output0(x-1,y);
        printf("D");
    }
    else{
        output0(x,y-1);
        printf("R");
    }
}

int main(){
    scanf("%d",&n);
    mst(mp2,0xf),mst(mp5,0xf),mst(mp0,0);
    rep(i,1,n+1) rep(j,1,n+1){
        scanf("%d",&x);
        mp2[i][j]=mp5[i][j]=0;
        if(x){
            while(x%2==0) mp2[i][j]++,x/=2;
            while(x%5==0) mp5[i][j]++,x/=5;
        }
        else mp0[i][j]=1;
    }
    mst(dp2,0xf),mst(dp5,0xf),mst(dp0,0);///
    rep(i,1,n+1) rep(j,1,n+1){
        if(i==1&&j==1) {
            dp2[i][j]=mp2[i][j];
            dp5[i][j]=mp5[i][j];
            dp0[i][j]=mp0[i][j];
        }
        else{
            dp2[i][j]=min(dp2[i-1][j],dp2[i][j-1])+mp2[i][j];
            dp5[i][j]=min(dp5[i-1][j],dp5[i][j-1])+mp5[i][j];
            dp0[i][j]=(dp0[i-1][j]||dp0[i][j-1]||mp0[i][j]);
        }
    }
    if(dp0[n][n]&&dp2[n][n]&&dp5[n][n]){///有零的路线存在
        puts("1");
        output0(n,n);
    }
    else{
        if(dp2[n][n]>=dp5[n][n]){
            printf("%d\n",dp5[n][n]);
            output5(n,n);
        }
        else if(dp5[n][n]>dp2[n][n]){
            printf("%d\n",dp2[n][n]);
            output2(n,n);
        }
    }
    puts("");
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值