Bessie 半夢半醒之間在數羊,她開始好奇:從 M 數到 N 的過程中,每個數碼(0–9)各出現了多少次?
例如 129 到 137:129, 130, 131, 132, 133, 134, 135, 136, 137,統計結果為 0 出現 1 次、1 出現 10 次、2 出現 2 次、3 出現 9 次、4 至 7 各 1 次、8 出現 0 次、9 出現 1 次。
輸入一行兩個整數 M 與 N(1 ≤ M ≤ N ≤ 2,000,000,000 且 N−M ≤ 500,000),輸出十個以空白分隔的整數。時間限制 10000ms,記憶體 1024kB。
看到 N 上限 20 億,直覺會認為需要逐位數的數學公式(digit DP)。但題目還給了一個關鍵限制:N − M ≤ 500,000。也就是說最多只需處理 50 萬個整數,每個整數最多 10 位,運算量約 500 萬次,暴力完全來得及。這正是本題的陷阱:先看清全部條件,再選演算法。
/*
* Dream Counting
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static int cnt[] = new int[10];
public static void main(String[] args) throws IOException {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String sn[] = cin.readLine().split(" ");
int a = Integer.parseInt(sn[0]);
int b = Integer.parseInt(sn[1]);
for (int i = a; i <= b; ++i) {
setcnt(i);
}
for (int i = 0; i < 10; ++i)
System.out.print(cnt[i] + " ");
System.out.println();
}
private static void setcnt(int n) {
if (n == 0)
cnt[0]++;
while (n > 0) {
int p = n % 10;
cnt[p]++;
n /= 10;
}
}
}
兩個實作細節值得注意:一是 n == 0 要特別處理,否則 while 迴圈根本不會執行;二是若改用 String.valueOf(i).charAt(j) 逐字元取數碼,寫法更短,效能差距在這個量級下可忽略。