解題思路
以題給字表將每個中文字轉成對應十進位數字,沒有十百千的位名運算。
去掉數值表示的前導零,先比較有效長度,再比較同長數字字串,即等於任意大非負整數比較。
數值相同時用原字串Unicode順序,保留全部重複項,再按指定分隔方式輸出原字串。
總字元L,n個數排序 O(n log n)次字串比較,最壞每次 O(Lmax);空間 O(L)。
Step-by-step animation
教學小例:中文逐位數字的數值排序
步驟 1 / 3
輸入八 12 二
轉成8、12、2
轉成8、12、2
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
string abc = "零一二三四五六七八九", s;
map<string, char> digit;
for (int i = 0; i < 10; i++)
digit[abc.substr(i * 3, 3)] = '0' + i;
vector<pair<pair<int, string>, string>> a;
while (cin >> s) {
string key;
if ((unsigned char)s[0] < 128)
key = s;
else
for (int j = 0; j < (int)s.size(); j += 3)
key += digit[s.substr(j, 3)];
auto p = key.find_first_not_of('0');
key = p == string::npos ? "0" : key.substr(p);
a.push_back({{key.size(), key}, s});
}
sort(a.begin(), a.end());
bool first = true;
for (auto v : a) {
if (!first)
cout << '\n';
first = false;
cout << v.second;
}
cout << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。