338. 計數問題
阿新 • • 發佈:2021-10-30
題目連結
338. 計數問題
給定兩個整數 \(a\) 和 \(b\),求 \(a\) 和 \(b\) 之間的所有數字中 \(0\sim 9\) 的出現次數。
例如,\(a=1024\),\(b=1032\),則 \(a\) 和 \(b\) 之間共有 \(9\) 個數如下:
1024 1025 1026 1027 1028 1029 1030 1031 1032
其中 0
出現 \(10\) 次,1
出現 \(10\) 次,2
出現 \(7\) 次,3
出現 \(3\) 次等等…
輸入格式
輸入包含多組測試資料。
每組測試資料佔一行,包含兩個整數 \(a\) 和 \(b\)。
當讀入一行為 0 0
時,表示輸入終止,且該行不作處理。
輸出格式
每組資料輸出一個結果,每個結果佔一行。
每個結果包含十個用空格隔開的數字,第一個數字表示 \(0\) 出現的次數,第二個數字表示 \(1\) 出現的次數,以此類推。
資料範圍
\(0<a,b<100000000\)
輸入樣例:
1 10
44 497
346 542
1199 1748
1496 1403
1004 503
1714 190
1317 854
1976 494
1001 1960
0 0
輸出樣例:
1 2 1 1 1 1 1 1 1 1 85 185 185 185 190 96 96 96 95 93 40 40 40 93 136 82 40 40 40 40 115 666 215 215 214 205 205 154 105 106 16 113 19 20 114 20 20 19 19 16 107 105 100 101 101 197 200 200 200 200 413 1133 503 503 503 502 502 417 402 412 196 512 186 104 87 93 97 97 142 196 398 1375 398 398 405 499 499 495 488 471 294 1256 296 296 296 296 287 286 286 247
解題思路
數位統計dp
- 時間複雜度:\(O()\)
程式碼
#include<bits/stdc++.h> using namespace std; int a,b; inline int get(vector<int> num,int l,int r) { int res=0; for(int i=l;i>=r;i--)res=res*10+num[i]; return res; } inline int power10(int x) { int res=1; while(x--)res*=10; return res; } int count(int n,int x) { if(!n)return 0; vector<int> nums; while(n) { nums.push_back(n%10); n/=10; } n=nums.size(); int res=0; for(int i=n-1-!x;~i;i--) { if(i<n-1) { res+=get(nums,n-1,i+1)*power10(i); if(!x)res-=power10(i); } if(nums[i]==x)res+=get(nums,i-1,0)+1; if(nums[i]>x)res+=power10(i); } return res; } int main() { while(scanf("%d%d",&a,&b),a||b) { if(a>b)swap(a,b); for(int i=0;i<=9;i++)printf("%d ",count(b,i)-count(a-1,i)); puts(""); } return 0; }