在网上看了一道笔试题,就是简单的dp,准备一下字节跳动夏令营的笔试
输入16进制数(1,2…f…)组成的矩阵,由左上角开始,到右下角,只能向右或下走,找出另走过的数的乘积的16进制数后缀0最少的方法。
#include<iostream>
using namespace std;
int nn[100][100];
int dp[100][100];
void myin(int n, int m)
{
char c;
for(int i = 0; i<m; i++)
{
for(int j = 0; j<n; j++)
{
cin >> hex >> nn[i][j];
}
}
}
int pls(int i, int j, int a, int b)
{
int plss = 0;
int miu = nn[i-a][j-b] * nn[i][j];
while(1)
{
if(miu % 16 == 0)
{
plss++;
miu /= 16;
}
else
break;
}
nn[i][j] = miu;
return plss;
}
int main()
{
int n,m;
cin >> n >> m;
myin(n, m);
for(int i = 0; i<m; i++)
{
for(int j = 0; j<n; j++)
{
if(i == 0 && j == 0)
dp[i][j] = 0;
else if(i == 0)
dp[i][j] = dp[i][j - 1] + pls(i,j,0,1);
else if(j == 0)
dp[i][j] = dp[i - 1][j] + pls(i,j,1,0);
else
dp[i][j] = dp[i][j - 1]<dp[i - 1][j]?(dp[i][j - 1] + pls(i,j,0,1)):(dp[i - 1][j] + pls(i,j,1,0));
}
}
printf("乘积矩阵:\n");
for(int i = 0; i<m; i++)
{
for(int j = 0; j<n; j++)
{
printf("%x ",nn[i][j]);
}
printf("\n");
}
printf("状态矩阵:\n");
for(int i = 0; i<m; i++)
{
for(int j = 0; j<n; j++)
{
printf("%d ",dp[i][j]);
}
printf("\n");
}
printf("最小末尾0:%d\n",dp[n-1][m-1]);
}