Bomb HDU - 3555(基础数位dp)

题目

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

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.

#include <cstdio>
#include <cstring>
#define ll long long 
using namespace std;
int dig[20];
ll dp[20][2][2];
ll dfs(int pos, int sta, int pre, int limit){
    if(pos == -1) return sta ? 1:0;
    if(!limit && dp[pos][sta][pre == 4] != -1) return dp[pos][sta][pre ==4 ];
    int up = limit ? dig[pos]:9;
    ll ans = 0;
    for(int i = 0; i <= up; i++){
        ans += dfs(pos-1, sta ||(pre == 4 && i == 9), i, limit && i == up);
    }
    if(!limit) dp[pos][sta][pre == 4] = ans;
    return ans; 
}
ll slove(ll x){
    int pos = 0;
    while(x){
        dig[pos++] = x%10;
        x /= 10;
    }
    ll ans = dfs(pos-1, 0, 0,1);
    return ans;
}
int main(){
    int t; 
    ll n;
    scanf("%d", &t);
    memset(dp, -1, sizeof(dp));
    while(t--){
        scanf("%I64d", &n);
        printf("%I64d\n", slove(n));
    }
    
    return 0;
}

sta与pre合并写

#include <cstdio>
#include <cstring>
#define ll long long 
using namespace std;
int dig[20];
ll dp[20][3];
int judge(int sta, int i){
	if(i == 4 && sta!= 2)
		return 1;
	else if((sta == 1 && i == 9) || sta == 2)
		return 2;
	else
		return 0;
}
ll dfs(int pos, int sta, int limit){
	if(pos == -1) return sta == 2 ? 1:0;
	if(!limit && dp[pos][sta]!= -1) return dp[pos][sta];
	int up = limit ? dig[pos]:9;
	ll ans = 0;
	for(int i = 0; i <= up; i++){
		ans += dfs(pos-1, judge(sta, i), limit && i == up);
	}
	if(!limit) dp[pos][sta] = ans;
	return ans; 
}
ll slove(ll x){
	int pos = 0;
	while(x){
		dig[pos++] = x%10;
		x /= 10;
	}
	ll ans = dfs(pos-1, 0,1);
	return ans;
}
int main(){
	int t; 
	ll n;
	scanf("%d", &t);
	memset(dp, -1, sizeof(dp));
	while(t--){
		scanf("%I64d", &n);
		printf("%I64d\n", slove(n));
	}
	
	return 0;
}

速度没啥差, 分开写还快点,空间换时间。

发布了52 篇原创文章 · 获赞 2 · 访问量 859

猜你喜欢

转载自blog.csdn.net/qq_44714572/article/details/103228460