hdu6796 X Number

题目链接

把每个数出现次数的数组当成状态来进行数位dp,常规的数位dp是枚举到最后一位或者此状态之前被处理过。
此题有个额外不同的地方就是,如果之前枚举的数不全是前导零且小于给定数,那么后面的数就可以随便放,因为我们只关心每个digital出现的次数而并不关心他们的位置,意味着我们可以直接求出此状态的方案。枚举d出现的次数,然后枚举每个digital出现次数进行转移就行。然后把这个状态的答案记录一下。

#include 
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
#define fi first
#define se second
#define pb push_back
#define wzh(x) cerr<<#x<<'='<
int t;
int d;
map<array<int, 10>, LL>dp[20][2];
int b[20], cnt;
array<int, 10>c;
LL f[20][20], co[22][22];
LL dfs(int x, int st, int lead) {
  if (!x) {
    for (int i = 0; i < 10; i++) {
      if (i != d && c[i] >= c[d])return 0;
    }
    return 1;
  }
  if (!st && !lead && dp[x][st].find(c) != dp[x][st].end()) {
    return dp[x][st][c];
  }
  if (!st && !lead) {
    int last = x;
    int x = 0;
    for (int i = 0; i < 10; i++) {
      if (i != d)x = max(x, c[i] + 1);
    }
    LL res = 0;
    for (int i = x; i <= c[d] + last; i++) { //枚举最高位放几个!
      int tmp = last - (i - c[d]); //还剩下这么多空位!

      if (tmp < 0)break;
      for (int j = 0; j <= 10; j++) {
        for (int k = 0; k <= tmp; k++)f[j][k] = 0;
      }
      f[0][0] = 1;
      for (int j = 1; j <= 10; j++) {
        if (j == d + 1) {
          for (int k = 0; k <= tmp; k++)f[j][k] = f[j - 1][k];
          continue;
        }
        for (int k = 0; k <= tmp; k++) { //加上这一位一共放了k个
          f[j][k] = f[j - 1][k];
          for (int q = 0; q < k; q++) { //之前放了q个
            if (c[j - 1] + k - q < i) {
              f[j][k] += f[j - 1][q] * co[last - q][k - q]; //转移
            }
          }
        }
      }
      res += f[10][tmp];
    }
    return dp[last][st][c] = res;
  }
  int up = st ? b[x] : 9;
  LL res = 0;
  for (int i = 0; i <= up; i++) {
    if (!i && lead) {
      res += dfs(x - 1, st && i == up, lead);
    } else {
      c[i]++;
      res += dfs(x - 1, st && i == up, 0);
      c[i]--;
    }
  }
  if (!st && !lead)dp[x][st][c] = res;
  return res;
}
LL gao(LL r) {
  cnt = 0;
  for (int i = 0; i < 10; i++)c[i] = 0;
  while (r) {
    b[++cnt] = r % 10;
    r /= 10;
  }
  return dfs(cnt, 1, 1);
}
LL l, r;

int main() {
  ios::sync_with_stdio(false);
  co[0][0] = 1;
  for (int i = 1; i <= 20; i++) {
    co[i][1] = i;
    for (int j = 2; j <= 20; j++) {
      co[i][j] = co[i - 1][j] + co[i - 1][j - 1];
    }
  }
  for (cin >> t; t; t--) {
    cin >> l >> r >> d;
    for (int i = 0; i < 20; i++)for (int j = 0; j < 2; j++)dp[i][j].clear();
    cout << gao(r) - gao(l - 1) << '\n';
  }
  return 0;
}

你可能感兴趣的:(dp)