B. The least round way

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);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值