您的位置:首页 > 其它

How many 0's? - POJ 3286 数位dp

2014-08-30 23:40 302 查看
How many 0's?

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 2967Accepted: 1582
Description

A Benedict monk No.16 writes down the decimal representations of all natural numbers between and including m and n, m ≤ n. How many 0's will he write down?

Input

Input consists of a sequence of lines. Each line contains two unsigned 32-bit integers m and n, m ≤ n. The last line of input has the value of m negative and this line should not be processed.

Output

For each line of input print one line of output with one integer number giving the number of 0's written down by the monk.

Sample Input
10 11
100 200
0 500
1234567890 2345678901
0 4294967295
-1 -1

Sample Output
1
22
92
987654304
3825876150


这道题和POJ2282一样,我就直接贴过来了。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
//dp[i][j]表示i位数中j的个数,dp0[i]表示i位数中合法的0的个数
ll dp[15][10],dp0[15],pow[15],n;
int num[15],len;
ll dfs(int pos,int N,int f)//f表示是否前面全是0,只对求0的个数有影响
{ if(pos<=0)
   return 0;
  ll ans=0;
  int i,j,k,m=num[pos];
  if(f==0)
  { ans+=m*dp[pos-1]
;
    if(N<m)
     ans+=pow[pos-1];
    else if(N==m)
     ans+=n%pow[pos-1]+1;
    ans+=dfs(pos-1,N,0);
  }
  else
  { ans+=(m-1)*dp[pos-1]
;
    ans+=dfs(pos-1,N,0);
    ans+=dp0[pos-1];
  }
  return ans;
}
ll solve(ll p,int N)
{ if(p<0)
   return -1;
  if(p==0)
   return 0;
  int i,j,k;
  len=0;n=p;
  while(p)
  { num[++len]=p%10;
    p/=10;
  }
  if(N==0)
   return dfs(len,N,1);
  else
   return dfs(len,N,0);
}
int main()
{ int i,j,k;
  ll l,r;
  pow[0]=1;
  for(i=1;i<=14;i++)
   pow[i]=pow[i-1]*10;
  for(i=1;i<=14;i++)
   for(j=0;j<=9;j++)
    dp[i][j]=dp[i-1][j]*10+pow[i-1];
  for(i=1;i<=14;i++)
   dp0[i]=9*dp[i-1][0]+dp0[i-1];
  while(~scanf("%I64d%I64d",&l,&r) && l!=-1)
  { if(l>r)
     swap(l,r);
    printf("%I64d\n",solve(r,0)-solve(l-1,0));
  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: