AcWing1083 Windy number (digit dp)

This question requires without leading zeros, so we're going to have a number of leading 0, enumerate again

The reason why the first two questions can be used directly with leading zero to do, because they do not affect the answers, such as the number of degrees, the first election without problems 0

Another example is the number of issues did not fall, even with leading 0, does not affect the answer, so you can not handle

But for a few windy, will affect the answers, such as a number of 0135, it stands to reason that 135 is in line with the answer, but not in line with leading 0, so this problem must deal with a leading 0

#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

const int N = 35;

int f[N][10];

void init()
{
    for (int i = 0; i <= 9; i ++ ) f[1][i] = 1;

    for (int i = 2; i < N; i ++ )
        for (int j = 0; j <= 9; j ++ )
            for (int k = 0; k <= 9; k ++ )
                if (abs(j - k) >= 2)
                    f[i][j] += f[i - 1][k];
}

int dp(int n)
{
    if (!n) return 0;

    vector<int> nums;
    while (n) nums.push_back(n % 10), n /= 10;

    int res = 0;
    int last = -2;
    for (int i = nums.size() - 1; i >= 0; i -- )
    {
        int x = nums[i];
        if (x)
        {
            for (int j = 1; j < x; j ++ )
                if (abs(last - j) >= 2)
                    res += f[i + 1][j];
            if (i != nums.size() - 1)
                if (abs(last - 0) >= 2)
                    res += f[i + 1][0];
        }

        if (abs(last - x) < 2) break;
        last = x;

        if (!i) res ++ ;
    }

    for (int i = 1; i < nums.size(); i ++ )
        for (int j = 1; j <= 9; j ++ )
            res += f[i][j];

    return res;
}

int main()
{
    init();

    int l, r;
    cin >> l >> r;

    cout << dp(r) - dp(l - 1) << endl;

    return 0;
}
View Code

 

Guess you like

Origin www.cnblogs.com/ctyakwf/p/12649960.html