题目链接:https://vjudge.net/problem/HDU-4352
题意:前面都是无关的话,只有倒数第二段与题目相关。意思就是寻找[L,R]之间数位最长上升子序列长度为K的数
解题思路:数位dp+状态压缩
可以用一个十位二进制数来保存最长上升子序列的情况,1的个数即最长上升子序列长度
使用dp[pos][state][k]来进行记忆化搜索,pos表示位置,state表示二进制状态,k表示当前要找的长度k
关于state的更新:
int update(int x, int state) {
for(int i = x;i<=9;i++)
if(state&(1<<i))
return (state^(1<<i))|(1<<x);
return state | (1 << x);
}
其他的就是标准的数位DP模板
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<math.h>
#include<string.h>
using namespace std;
#define ll long long
int t;
ll L, R, K;
int num[20];
ll dp[20][2000][20]; // pos state K
int update(int x, int state) {
for(int i = x;i<=9;i++)
if(state&(1<<i))
return (state^(1<<i))|(1<<x);
return state | (1 << x);
}
int cal(int x) {
int cnt = 0;
for (int i = 0; i <= 9; i++) {
if (x & (1 << i))
cnt++;
}
return cnt;
}
ll dfs(int pos,int limit,int state,int k,int pre) {
if (!limit && dp[pos][state][k] != -1) {
return dp[pos][state][k];
}
if (pos == 0) {
return cal(state) == k;
}
int up = limit ? num[pos] : 9;
ll res = 0;
for (int i = 0; i <= up; i++) {
res += dfs(pos - 1, limit&&i==up, (pre==0&&i==0) ? 0 : update(i,state), k, pre||(i!=0));
}
if (!limit)
return dp[pos][state][k] = res;
else
return res;
}
ll solve(ll x) {
int cnt = 0;
while (x) {
num[++cnt] = x % 10;
x /= 10;
}
ll res = dfs(cnt, 1, 0, K, 0);
return res;
}
int main() {
memset(dp, -1, sizeof(dp));
cin >> t;
int cas = 1;
while (t--) {
cin >> L >> R >> K;
printf("Case #%d: %lld\n", cas++,solve(R) - solve(L - 1));
}
return 0;
}