1.转角路径的乘积中最多能有几个尾随零–前缀和思想、10的倍数的处理
周赛第三题,想到了前缀和的思想,但是没有想到如何巧妙的保存结果,使得结果既能保存为10的倍数的信息,又不占用过多空间。
事实上,乘尾随0的个数,就是所有乘数因子中,2和5的个数中的最小值。
具体代码如下:
typedef struct multi{
pair<int,int> left,right,up,down;
}multi;
class Solution {
public:
int maxTrailingZeros(vector<vector<int>>& grid) {
int ans=0;
int m=grid.size(),n=grid[0].size();
vector<vector<multi>> temp(m,vector<multi>(n));
vector<vector<pair<int,int>>> A(m,vector<pair<int,int>>(n));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
temp[i][j].left.first=0;
temp[i][j].right.first=0;
temp[i][j].up.first=0;
temp[i][j].down.first=0;
temp[i][j].left.second=0;
temp[i][j].right.second=0;
temp[i][j].up.second=0;
temp[i][j].down.second=0;
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int a=grid[i][j];
while(a%2==0){
a/=2;
A[i][j].first++;
}
a=grid[i][j];
while(a%5==0){
a/=5;
A[i][j].second++;
}
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(j-1>=0){
temp[i][j].left.first+=temp[i][j-1].left.first+A[i][j-1].first;
temp[i][j].left.second+=temp[i][j-1].left.second+A[i][j-1].second;
}
if(i-1>=0){
temp[i][j].up.first+=temp[i-1][j].up.first+A[i-1][j].first;
temp[i][j].up.second+=temp[i-1][j].up.second+A[i-1][j].second;
}
}
}
for(int i=m-1;i>=0;i--){
for(int j=n-1;j>=0;j--){
if(j+1<n){
temp[i][j].right.first+=temp[i][j+1].right.first+A[i][j+1].first;
temp[i][j].right.second+=temp[i][j+1].right.second+A[i][j+1].second;
}
if(i+1<m){
temp[i][j].down.first+=temp[i+1][j].down.first+A[i+1][j].first;
temp[i][j].down.second+=temp[i+1][j].down.second+A[i+1][j].second;
}
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int a = min(temp[i][j].left.first + temp[i][j].up.first + A[i][j].first, temp[i][j].left.second + temp[i][j].up.second + A[i][j].second);
int b = min(temp[i][j].left.first + temp[i][j].down.first + A[i][j].first, temp[i][j].left.second + temp[i][j].down.second + A[i][j].second);
int c = min(temp[i][j].right.first + temp[i][j].up.first + A[i][j].first, temp[i][j].right.second + temp[i][j].up.second + A[i][j].second);
int d = min(temp[i][j].right.first + temp[i][j].down.first + A[i][j].first, temp[i][j].right.second + temp[i][j].down.second + A[i][j].second);
ans=max(ans,max(max(a,b),max(c,d)));
}
}
return ans;
}
};