您的位置:首页 > 其它

HDU 3555 Bomb

2013-04-30 08:22 162 查看
[b]Bomb[/b]

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)

Total Submission(s): 3338 Accepted Submission(s): 1177

[align=left]Problem Description[/align]
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?

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each test case, output an integer indicating the final points of the power.

[align=left]Sample Input[/align]

3
1
50
500

[align=left]Sample Output[/align]

0
1
15

Hint

From 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.

最为基本的数位DP问题,寻找含有49的数字,可以用递推和DFS两种方法写
本题代码稍加修改即可适用于各种有附加条件的数位DP题

递推法:

[C]

#include<stdio.h>
#include<string.h>

int num[20];
long long n;
//dp[i][j]表示计算到第i位时,状态为j的数的个数
//j=0表示之前不含49且该位不是9,j=1表示之前不含49但该位是4,j=2表示之前已经包含49
long long dp[20][3];

//dfs函数:pos为当前所处的位,flag记录状态(即dp数组的第二维),limit表示前一位是否达到了其最大值,若达到则后面的一位的上限会有限制
unsigned long long dfs(int pos,int flag,int limit)
{
int end,i,have;
unsigned long long sum=0;
if(pos==-1)
return flag==2;
if((!limit)&&(dp[pos][flag]!=-1))
return dp[pos][flag];

end=limit?num[pos]:9;
for(i=0;i<=end;i++)
{
have=flag;
if(flag==1&&i==9)
have=2;
if(flag==0&&i==4)
have=1;
if(flag==1&&i!=4&&i!=9)
have=0;
sum+=dfs(pos-1,have,limit&&i==end);
}
if(!limit)
return dp[pos][flag]=sum;
return sum;
}

//col()函数,将待处理的大整数按位分解存入num数组中
unsigned long long col()
{
int pos=0;
while(n)
{
num[pos++]=n%10;
n/=10;
}
return dfs(pos-1,0,1);
}

int main()
{
int t;
scanf("%d",&t);

while(t--)
{
scanf("%I64d",&n);
memset(dp,-1,sizeof(dp));
printf("%I64d\n",col());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: