zoukankan      html  css  js  c++  java
  • 洛谷P2657 [SCOI2009]windy数 题解 数位DP

    题目链接:https://www.luogu.com.cn/problem/P2657
    题目大意:找区间 \([A,B]\) 范围内 不含前导零相邻两个数字之差至少为2 的正整数的个数。
    题目分析:

    这道题目使用 数位DP 进行求解。

    这里有两个条件:

    1. 不含前导零;
    2. 相邻两个数字之差至少为2。

    所以我们需要确定的是,对于当前状态:

    1. 他的前一位的数字是啥;
    2. 他的前面是不是都是前导0。

    我们可以开一个函数 dfs(int pos, int pre, bool all0, bool limit) 进行求解,其中:

    • pos 表示当前所处的数位;
    • pre 表示前一位的数字;
    • all0 表示当前状态之前的那些位是不是都是0;
    • limit 表示当前是否处于限制条件内。

    实现代码如下:

    #include <bits/stdc++.h>
    using namespace std;
    int f[33][10][2], a[33];
    void init() {
        memset(f, -1, sizeof(f));
    }
    int dfs(int pos, int pre, bool all0, bool limit) {
        if (pos < 0) return 1;
        if (!limit && f[pos][pre][all0] != -1) return f[pos][pre][all0];
        int up = limit ? a[pos] : 9;
        int tmp = 0;
        for (int i = 0; i <= up; i ++) {
            if (!all0 && abs(i-pre) < 2) continue;
            tmp += dfs(pos-1, i, all0 && i==0, limit && i==up);
        }
        if (!limit) f[pos][pre][all0] = tmp;
        return tmp;
    }
    int get_num(int x) {
        int pos = 0;
        while (x) {
            a[pos++] = x % 10;
            x /= 10;
        }
        return dfs(pos-1, 0, true, true);
    }
    int A, B;
    int main() {
        init();
        cin >> A >> B;
        cout << get_num(B) - get_num(A-1) << endl;
        return 0;
    }
    
  • 相关阅读:
    微信app支付,服务端对接
    git 忽略文件权限
    linux 终端全局代理设置
    centos 谷歌浏览器安装
    putty快速设置本地代理
    centos rpmforge repo
    mysql 同步
    apscheduler 排程
    tornado 排程
    gedit 格式化json
  • 原文地址:https://www.cnblogs.com/quanjun/p/11965718.html
Copyright © 2011-2022 走看看