【HDU 3555】Bomb(数位dp)
Bomb
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 12923 Accepted Submission(s): 4619
Problem Description
The counter-terrorists found a time bomb in the dust. But this time the terrorists improve on the time bomb. The number sequence of the time bomb counts from 1 to N. If the current number sequence includes the sub-sequence “49”, the power of the blast would add one point.
Now the counter-terrorist knows the number N. They want to know the final points of the power. Can you help them?
Input
The first line of input consists of an integer T (1 <= T <= 10000), indicating the number of test cases. For each test case, there will be an integer N (1 <= N <= 2^63-1) as the description.
The input terminates by end of file marker.
Output
For each test case, output an integer indicating the final points of the power.
Sample Input
3
1
50
500
Sample Output
0
1
15
HintFrom 1 to 500, the numbers that include the sub-sequence “49” are “49”,”149”,”249”,”349”,”449”,”490”,”491”,”492”,”493”,”494”,”495”,”496”,”497”,”498”,”499”,
so the answer is 15.
[题意][求出1到n中含有’49’的数的个数]
**【题解】【数位dp】
【状态:f[i][j]表示i位数所有以j开头的数中合法(不含“49”)的数的个数。】
【转移:if (j!=4||k!=9) f[i][j]+=f[i-1][k];枚举jk分别为i和i-1位数的开头并且满足条件。 】
【求解时用总数减去dp值。 】
【实际上,数位dp是先dp,再按数据查找符合要求的项】**
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
ll n,t;
ll f[50][50],h[50],ans;
void dp()
{
f[0][0]=1;
int i,j,k;
for(k=1;k<20;++k)
for(i=0;i<10;++i)
for(j=0;j<10;++j)
if(i!=4||j!=9)
f[k][i]+=f[k-1][j];
}
inline ll math(ll n)
{
ll i,j,tot=0,sum=0;
memset(h,0,sizeof(h));
while(n)
h[++tot]=n%10,n/=10;
h[1]++;
for(i=1;i<=tot;++i)
if(h[i]>=10)
h[i+1]+=h[i]/10,h[i]%=10;
if(h[tot+1]) tot++;
for(i=tot;i>0;i--)
{
for(j=0;j<h[i];++j)
if(j!=9||h[i+1]!=4) sum+=f[i][j];
if(h[i]==9&&h[i+1]==4) break;
}
return sum;
}
int main()
{
int i;
dp();
scanf("%I64d",&t);
for(i=1;i<=t;++i)
{
scanf("%I64d",&n);
ans=math(n); ans=n-ans; ans++;
printf("%I64d\n",ans);
}
return 0;
}
[窝是第一次写数位dp……]