題目鏈接:ZJOI2010 count 數字計數
題意就是統計某個區間之內的各個數碼出現的次數。明顯的數位dp。
這裏的做法事實上可以進一步的通過空間換時間,比如在dp記錄中增加num和lead狀態,這樣可以減少後續的遞歸次數。大概可以從18ms減少到11ms。
#include <iostream>
#include <limits.h>
#include <vector>
#include <string>
#include <stdlib.h>
#include <algorithm>
#include <map>
#include <cstdlib>
#include <stack>
#include <set>
#include <cmath>
#include <queue>
#include <stdio.h>
#include <cstring>
//#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 20;
const int maxm = 102;
const int inf = 0x3f3f3f3f;
const ll llinf = 0x3f3f3f3f3f3f3f3f;
const double dinf = 1061109567.0;
const int mod = 1e9 + 7;
ll dp[maxn][maxn];
int a[maxn];
ll sum1[maxn], sum2[maxn];
ll dfs(int pos, ll sum, int num, bool lead, bool limit) {
if (pos == -1) {//在前綴合法的情況下返回貢獻值
return (ll)sum;
}
if (!lead && !limit && dp[pos][sum] != -1)//在不保存lead的結果的前提下必須在沒有前導零的情況下計算貢獻,
//否則只能在dp中設置新的狀態來保存lead
return dp[pos][sum];//dp狀態的設置之所以不能僅僅使用pos和num是因爲子問題不能由num來表示,
//而只能使用sum來表示,即pos和sum能唯一標識一個子問題。當然可以增加狀態來減少遞歸深度,
//比如增加lead欄可以使得總時間減少大概8ms
int up = limit ? a[pos] : 9;
ll res = 0;
int tmp = 0;
for (int i = 0; i <= up; ++i) {
if (i == 0 && lead)//如果有前導零,則不算進總貢獻
res += dfs(pos - 1, sum, num, lead, limit && (i == up));
else//否則加入結果中
res += dfs(pos - 1, sum + (i == num), num, lead && (i == 0), limit && (i == up));
}
if (!lead && !limit)
dp[pos][sum] = res;
return res;
}
void solve(ll x, ll sum[]) {
int len = 0;
while (x) {
a[len++] = x % 10;
x /= 10;
}
for (int i = 0; i < 10; i++) {
sum[i] = dfs(len - 1, 0, i, 1, 1);
}
}
int main() {
// freopen("input.txt","r",stdin);
ll n, m;
while (scanf("%lld%lld", &m, &n) == 2 && (n != 0 && m != 0)) {
memset(dp, -1, sizeof(dp));
solve(n, sum1);
solve(m - 1, sum2);
for (int i = 0; i < 10; ++i) {
printf("%lld", sum1[i] - sum2[i]);
if (i < 9)
printf(" ");
}
puts("");
}
return 0;
}