hihocoder1241 : Best Route in a Grid
2015-10-12 10:09
295 查看
题目链接:
传送门题意:
给定一个n*n的矩阵,每次只能往下或者往左走,而且0的位置不能走,求最后走的格子的数的乘积末尾连续0的最小个数。分析:
很明显最后末尾连续0的个数和素因子2和素因子5的数量有关。那么我们就做两次dp,设dp[i][j]表示走的(i,j)的时候素因子2/5的最小的个数。然后那就是一个简单的dp了。Code:
#include <bits/stdc++.h> using namespace std; const int maxn = 1e3+10; int a[maxn][maxn]; int dp[maxn][maxn]; int cnt1[maxn][maxn]; int cnt2[maxn][maxn]; const int inf = 1000000; int fen(int x,int f) { int num = 0; while(x%f==0) { num++; x=x/f; } return num; } void debug() { cout<<"======================"<<endl; for(int i=0; i<=n; i++) { for(int j=0; j<=n; j++) { cout<<dp[i][j]<<" "; } cout<<endl; } cout<<"======================"<<endl; } int main() { int n; while(~scanf("%d",&n)) { for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) scanf("%d",&a[i][j]); } memset(cnt1,0,sizeof(cnt1)); memset(cnt2,0,sizeof(cnt2)); for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { if(!a[i][j]) { cnt1[i][j]=inf; cnt2[i][j]=inf; } else { cnt1[i][j]=fen(a[i][j],2); cnt2[i][j]=fen(a[i][j],5); } } } for(int i=0; i<=n; i++) dp[i][0]=dp[0][i]=inf; dp[1][0]=0,dp[0][1]=0; for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { dp[i][j]=min(dp[i][j-1],dp[i-1][j])+cnt1[i][j]; } } int tmp = dp ; for(int i=0; i<=n; i++) dp[i][0]=dp[0][i]=inf; dp[1][0]=dp[0][1]=0; for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { dp[i][j]=min(dp[i][j-1],dp[i-1][j])+cnt2[i][j]; } } printf("%d\n",min(tmp,dp )); } return 0; } /*** 3 2 5 2 2 5 2 2 5 2 5 5 5 5 2 2 5 5 5 2 2 5 5 5 2 2 5 5 5 2 2 5 5 5 2 2 ****/
相关文章推荐
- hihocoder:hiho一下第二十八周之二叉堆
- hihocoder #1091
- 在线编程刷题碰到的一些问题
- hihocoder题库1014
- hihocoder题库1000
- hihocoder #1035 : 自驾旅行 III 树形DP
- 初识splay tree ( hihocoder #1034 : 毁灭者问题 题解)
- hihocoder 1033 交错和
- hihoCoder #1051 补提交卡
- hihoCoder第二周:Trie树
- hihoCoder第一周:求解最大回文串
- 堆——hihoCoder "hiho一下 第二十八周"题目解析
- 【数据结构——树】Trie树的两种实现方式:二叉树(左孩子右兄弟)与二十六叉树
- RMQ_Sparse Table & Segment Tree
- Hihocoder 1086 Browser Caching
- hihoCoder 1128 二分·二分查找
- hihoCoder 二分·二分查找之k小数
- hihoCoder 1043 完全背包
- # hihocoder #1093 : 最短路径·三:SPFA算法
- #hihocoder #1135 : Magic Box