ACdream 1064 完美数【数位DP】

来源:互联网 发布:多线程cpu优化 编辑:程序博客网 时间:2024/05/20 04:09

8是中国人很喜欢的一个数字,但是如果有3的存在就变成了38,就不是很好了。。

你能告诉我,在[L, R] 的正整数区间内,要么包含3 要么包含 8 的不同的整数有多少个么?

Input
第一行一个整数T (T ≤ 10000),代表数据的组数

对于每组数据给两个整数 L, R (1 ≤ L ≤ R ≤ 1e9)

Output
对于每组数据,给一个整数为答案。
Sample Input
3
1 100
1 3
8 8
Sample Output
34
1
1

分析:限制条件为3、8,那么情况就是含3、含8、含38、含其他。

个人:感觉对数位DP的理解还是不太行。再多体会体会吧。

#include<iostream>#include<cstring>#include<algorithm>#include<cstdio>using namespace std;int dp[11][4];int num[11];int pos;int L, R;// top==1 到达上限int dfs(int pos, int s, int top)//3 0 1 2{    if (s == 2)        return 0;    if (pos == -1)        return s == 1 || s == 0;    if (top == 0 && dp[pos][s] != -1)        return dp[pos][s];    int lmt = top ? num[pos] : 9;    int sum = 0;    for (int i = 0; i <= lmt; i++)    {        int cs = s;        if (s == 2)            cs = 2;        else        {            if (s == 3 && i == 3)                cs = 0;            if (s == 3 && i == 8)                cs = 1;            if (s == 0 && i == 8)                cs = 2;            if (s == 1 && i == 3)                cs = 2;            if (s == 3 && i != 3 && i != 8)                cs = 3;        }        sum += dfs(pos-1, cs, top&&i == lmt);    }    return top ? sum : dp[pos][s] = sum;}int solve(int x){    pos = 0;    while (x > 0)    {        num[pos++] = x % 10;        x /= 10;    }    memset(dp, -1, sizeof dp);;    return dfs(pos - 1, 3, 1);}int main(){    int t;    scanf("%d", &t);    while (t--)    {        scanf("%d %d", &L, &R);        printf("%d\n", solve(R) - solve(L - 1));    }    return 0;}
原创粉丝点击