hdu 5787 K-wolf Number (数位dp)
K-wolf Number
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 737 Accepted Submission(s): 265
Problem Description
Alice thinks an integer x is a K-wolf number, if every K adjacent digits in decimal representation of x is pairwised different.
Given (L,R,K), please count how many K-wolf numbers in range of [L,R].
Given (L,R,K), please count how many K-wolf numbers in range of [L,R].
Input
The input contains multiple test cases. There are about 10 test cases.
Each test case contains three integers L, R and K.
1≤L≤R≤1e18
2≤K≤5
Each test case contains three integers L, R and K.
1≤L≤R≤1e18
2≤K≤5
Output
For each test case output a line contains an integer.
Sample Input
1 1 2
20 100 5
Sample Output
1
72
建立一个pre[]数组来传递一个数之前四个数的值,传递时检查一下前面k - 1个值是否符合条件,注意dfs时去除前导0的影响就好了。
#include <bits/stdc++.h> using namespace std; #define ll long long int dig[20]; ll dp[20][11][11][11][11]; ll l, r, k; ll dfs(int pos, int pre[], int lim, int zero) { if(pos == -1) { //for(int i = 1; i <= 4; i++) printf("%d ", pre[i]); puts(""); return 1; } ll& tmp = dp[pos][pre[1]][pre[2]][pre[3]][pre[4]]; if(!lim && tmp != -1) return tmp; int End = lim ? dig[pos] : 9; ll ret = 0; for(int i = 0; i <= End; i++) { int flag = 0; int tmpPre[5]; for(int j = 1; j <= k - 1; j++) if(i == pre[j]) { flag = 1; break; } if(flag) continue; for(int j = 2; j <= 4; j++) tmpPre[j] = pre[j - 1]; if(zero && !i) tmpPre[1] = 10; else tmpPre[1] = i; if(zero && !i) ret += dfs(pos - 1, tmpPre, lim && (i == End), 1); else ret += dfs(pos - 1, tmpPre, lim && (i == End), 0); } if(!lim) tmp = ret; return ret; } ll func(ll num) { int n = 0; while(num) { dig[n++] = num % 10; num /= 10; } int pre[5]; for(int i = 1; i <= 4; i++) pre[i] = 10; return dfs(n - 1, pre, 1, 1); } int main() { while(~scanf("%I64d %I64d %I64d", &l, &r, &k)) { memset(dp, -1, sizeof(dp)); printf("%I64d\n", func(r) - func(l - 1)); } }