Codeforces Beta Round #2 B. The least round way dp
B. The least round way
题目连接:
http://www.codeforces.com/contest/2/problem/B
Description
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.
Sample Input
3
1 2 3
4 5 6
7 8 9
Sample Output
0
DDRR
Hint
题意
给你一个n*n的矩阵
然后这个矩阵你需要从左上角走到右下角
只能走右或者向下。
你要使得你经过的数,乘积起来后面的0的个数最少。
题解:
dp[i][j][0]表示到i,j位置,2的因子最少多少个
dp[i][j][1]表示到i,j位置,5的因子最少多少个
然后答案显然就是min(dp[n][n][0],dp[n][n][1])了,然后倒着dfs输出答案就好了。
但是这儿有一个hack点,就是如果有一个位置是0的话,答案就最多为1了,这个是显然的嘛。
然后就没了。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1100;
const int inf = 1e9;
int dp[maxn][maxn][2];
int cnt[maxn][maxn][2];
int g[maxn][maxn][2];
int n,a[maxn][maxn];
void solve(int x,int y,int now)
{
if(x==1&&y==1)return;
if(g[x][y][now]==1)solve(x-1,y,now),printf("D");
else solve(x,y-1,now),printf("R");
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&a[i][j]);
int flagx=0,flagy=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i][j]==0)
{
flagx=i,flagy=j;
break;
}
int pre = a[i][j];
while(a[i][j]%2==0)cnt[i][j][0]++,a[i][j]/=2;
while(a[i][j]%5==0)cnt[i][j][1]++,a[i][j]/=5;
}
}
memset(dp,0x3f,sizeof(dp));
memset(g,0,sizeof(g));
dp[1][1][0]=cnt[1][1][0],dp[1][1][1]=cnt[1][1][1];
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i==1&&j==1)continue;
for(int k=0;k<2;k++)
{
dp[i][j][k]=cnt[i][j][k]+min(dp[i-1][j][k],dp[i][j-1][k]);
if(dp[i-1][j][k]<dp[i][j-1][k])g[i][j][k]=1;
}
}
}
int ans = min(dp[n][n][0],dp[n][n][1]);
int st;
if(dp[n][n][0]<dp[n][n][1])st=0;
else st=1;
if(ans==0)puts("0");
else if(flagx&&flagy)
{
puts("1");
int nowx=1,nowy=1;
while(nowx<flagx)nowx++,printf("D");
while(nowy<flagy)nowy++,printf("R");
while(nowx<n)nowx++,printf("D");
while(nowy<n)nowy++,printf("R");
return 0;
}
else printf("%d\n",ans);
solve(n,n,st);
}