数位DP BZOJ 1026 [SCOI2009]windy数
前面全是0的情况特判
#include <bits/stdc++.h> int dp[10][10]; int digit[10]; int DFS(int pos, int val, int zero, bool limit) { if (pos == -1) { return 1; } int &now = dp[pos][val]; if (!limit && zero && now != -1) { return now; } int d = limit ? digit[pos] : 9; int ret = 0; if (zero == 0) { for (int i=0; i<=d; ++i) { ret += DFS (pos - 1, i, i, limit && i == d); } } else { for (int i=0; i<=d; ++i) { if ((i-val) * (i - val) < 4) { continue; } ret += DFS (pos - 1, i, 1, limit && i == d); } } if (!limit && zero) { now = ret; } return ret; } int solve(int x) { int n = 0; while (x) { digit[n++] = x % 10; x /= 10; } int ret = 0; return DFS (n - 1, 0, 0, true); } int main() { memset (dp, -1, sizeof (dp)); int a, b; while (scanf ("%d%d", &a, &b) == 2) { printf ("%d\n", solve (b) - solve (a - 1)); } return 0; }
编译人生,运行世界!