# HDU-5787 K-wolf Number(数位DP)

(2016 Multi-University Training Contest 5)

#include <bits/stdc++.h>
#define LL long long
using namespace std;
LL dp[18][11][11][11][11], L, R;
int num[18], K;
LL dfs(int pos, int limit, int lead, int pre1, int pre2, int pre3, int pre4)
{
if(pos == -1) return 1;
if(!limit && !lead && pos+1 >= K && dp[pos][pre1][pre2][pre3][pre4] != -1)
return dp[pos][pre1][pre2][pre3][pre4];
int up = limit? num[pos]: 9;
LL tmp = 0;
for(int i = 0, j; i <= up; ++i)
{
{
tmp += dfs(pos-1, limit&&i==num[pos], 1, 10, 10, 10, 10);
continue;
}
if(pre1!=i && pre2!=i && pre3!=i && pre4!=i)
{
tmp += dfs(pos-1, limit&&i==num[pos], lead&&i==0, K>1?i:10, K>2?pre1:10, K>3?pre2:10, K>4?pre3:10);
}
}
if(!limit && !lead && pos+1 >= K) dp[pos][pre1][pre2][pre3][pre4] = tmp;
return tmp;
}
LL solve(LL x)
{
int pos = 0;
while(x)
{
num[pos++] = x%10;
x /= 10;
}
return dfs(pos-1, 1, 1, 10, 10, 10, 10);
}
int main()
{
while(~scanf("%lld %lld %d", &L, &R, &K))
{
memset(dp, -1, sizeof dp);
printf("%lld\n", solve(R)-solve(L-1));
}
return 0;
}

#include <bits/stdc++.h>
#define LL long long
using namespace std;
LL dp[18][11][11][11][11], L, R;
int num[18], K;
LL dfs(int pos, int limit, int lead, int pre1, int pre2, int pre3, int pre4)
{
if(pos == -1) return 1;
if(!limit && dp[pos][pre1][pre2][pre3][pre4] != -1)
return dp[pos][pre1][pre2][pre3][pre4];
int up = limit? num[pos]: 9;
LL tmp = 0;
for(int i = 0, j; i <= up; ++i)
{
{
tmp += dfs(pos-1, limit&&i==num[pos], 1, 10, 10, 10, 10);
continue;
}
if(pre1!=i && pre2!=i && pre3!=i && pre4!=i)
{
tmp += dfs(pos-1, limit&&i==num[pos], lead&&i==0, K>1?i:10, K>2?pre1:10, K>3?pre2:10, K>4?pre3:10);
}
}
if(!limit) dp[pos][pre1][pre2][pre3][pre4] = tmp;
return tmp;
}
LL solve(LL x)
{
int pos = 0;
while(x)
{
num[pos++] = x%10;
x /= 10;
}
return dfs(pos-1, 1, 1, 10, 10, 10, 10);
}
int main()
{
while(~scanf("%lld %lld %d", &L, &R, &K))
{
memset(dp, -1, sizeof dp);
printf("%lld\n", solve(R)-solve(L-1));
}
return 0;
}

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客