Codecraft-18 and Codeforces Round #458 (Div. 1 + Div. 2, combined) C】 Travelling Salesman and Specia

数位dp

预处理1-1000中经过刚好经过k-1次变换到1的数.
然后搞一个数位dp, 当limit为false的时候可以在后面用组合数放置1.
要特判k==0(只有1满足)k==1(1不满足要减去)

#include 
using namespace std;
vector<int> vec;
template<class T>
T read()
{
    T x = 0, f = 1; char ch = getchar();
    while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
    while(ch >= '0' && ch <= '9') {x = 10 * x + ch - '0'; ch = getchar();}
    return x * f;
}
int a[1010];
char s[1010];
int one[1010];
const long long mod = 1e9 + 7;
long long dp[1010][1010];
bool is[1010];
long long C[1010][1010];
inline int lowbit(int x)
{
    return x & (-x);
}

long long dfs(int pos, int num, bool limit)
{
    if(pos == -1) return is[num] == true;
    if(!limit && ~dp[pos][num]) return dp[pos][num];
    long long res = 0;
    if(limit)
        for(int i = 0; i <= a[pos]; ++i)
            res = (res + dfs(pos - 1, num + (i == 1), limit && i == a[pos])) % mod;
    else
    {
        for(auto u : vec)
        {
            if(u > num + pos + 1) break;
            if(u < num) continue;
            res = (res + C[pos + 1][u - num]) % mod;
        }
    }
    return limit ? res : dp[pos][num] = res;
}
long long get()
{
    int len = strlen(s);
    for(int i = 0; i < len; ++i) a[i] = s[len - i - 1] - '0';
    return dfs(len - 1, 0, true);
}
int main()
{
    one[0] = 0;
    for(int i = 1; i <= 1000; ++i) one[i] = one[i ^ lowbit(i)] + 1;
    scanf("%s", s);
    memset(dp, -1, sizeof dp);
    memset(is, false, sizeof is);
    int k = read<int>();
    if(k == 0) return puts("1"), 0;
    for(int i = 1; i <= 1000; ++i)
    {
        int t = k, tmp = i, f = 1;
        while(--t)
        {
            if(tmp == 1) f = 0;
            tmp = one[tmp];
        }
        if(f && tmp == 1)
        {
            vec.push_back(i);
            is[i] = 1;
        }
    }
    C[0][0]= 1;
    for(int i = 1; i <= 1000; ++i) C[i][0] = C[i][i] = 1;
    for(int i = 2; i <= 1000; ++i)
        for(int j = 1; j < i; ++j) C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod;
    printf("%I64d\n", (get() + (mod - 1) * (k == 1)) % mod);
    return 0;
}

你可能感兴趣的:(动态规划-dp)