题目描述
题目定义“谦逊数”为只包含质因子 222、333、555 和 777 的正整数(111 也被视为谦逊数)。序列的前 202020 项为:
1,2,3,4,5,6,7,8,9,10,12,14,15,16,18,20,21,24,25,27,…
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, \dots
1,2,3,4,5,6,7,8,9,10,12,14,15,16,18,20,21,24,25,27,…
对于每个输入的 nnn(1≤n≤58421 \le n \le 58421≤n≤5842),输出第 nnn 个谦逊数,并要求使用正确的序数后缀(st、nd、rd、th)。
输入格式
输入包含多个测试用例,每行一个整数 nnn。输入以 n=0n = 0n=0 结束。
输出格式
对于每个 nnn,输出一行,格式为:
The nth humble number is number.
其中 n 为输入的数字,number 为第 nnn 个谦逊数,th 应替换为正确的序数后缀。
样例
输入
1
2
3
4
11
12
13
21
22
23
100
1000
5842
0
输出
The 1st humble number is 1.
The 2nd humble number is 2.
The 3rd humble number is 3.
The 4th humble number is 4.
The 11th humble number is 12.
The 12th humble number is 14.
The 13th humble number is 15.
The 21st humble number is 28.
The 22nd humble number is 30.
The 23rd humble number is 32.
The 100th humble number is 450.
The 1000th humble number is 385875.
The 5842nd humble number is 2000000000.
题目分析
本题的核心是生成谦逊数序列的第 111 到第 584258425842 项。
生成方法
可以使用类似“丑数”生成的算法。设已知前 i−1i-1i−1 个谦逊数,第 iii 个谦逊数是已生成谦逊数乘以 222、333、555 或 777 中的最小值,且之前未出现过。具体实现可以使用最小堆(优先队列)和集合去重:
- 初始将 111 加入最小堆和集合。
- 重复 584258425842 次:
- 从堆中弹出最小值(即下一个谦逊数)。
- 将该数乘以 222、333、555、777 得到四个新数,若未出现过则加入堆和集合。
- 将弹出的数按顺序存入数组。
由于 nnn 最大为 584258425842,生成的谦逊数最大值不超过 2×1092 \times 10^92×109(如样例所示),使用 646464 位整数存储即可。
序数后缀规则
- 特殊情况:111111、121212、131313 的后缀为
th。 - 一般情况:
- 个位为 111 且不是 111111:
st - 个位为 222 且不是 121212:
nd - 个位为 333 且不是 131313:
rd - 其他:
th
- 个位为 111 且不是 111111:
复杂度分析
生成 584258425842 个谦逊数,每个数生成 444 个后继,堆操作 O(logN)O(\log N)O(logN),总复杂度 O(KlogK)O(K \log K)O(KlogK),其中 KKK 约为 5842×45842 \times 45842×4,完全可接受。
代码实现
// Humble Numbers
// UVa ID: 443
// Verdict: Accepted
// Submission Date: 2016-07-15
// UVa Run Time: 0.000s
//
// 版权所有(C)2016,邱秋。metaphysis # yeah dot net
#include <bits/stdc++.h>
using namespace std;
typedef long long int bigNumber;
int main(int argc, char *argv[])
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
int factors[4] = {2, 3, 5, 7};
set<bigNumber> uglyNumbers;
map<int, bigNumber> humbleNumbers;
priority_queue<bigNumber, vector<bigNumber>, greater<bigNumber>> candidates;
candidates.push(1);
for (int i = 1; i <= 5842; i++)
{
bigNumber top;
do
{
top = candidates.top();
candidates.pop();
} while (uglyNumbers.count(top) > 0);
humbleNumbers[i] = top;
uglyNumbers.insert(top);
for (int j = 0; j < 4; j++)
{
bigNumber next = top * factors[j];
if (uglyNumbers.count(next) == 0)
candidates.push(next);
}
}
int n;
while (cin >> n, n)
{
int number = humbleNumbers[n];
if ((n % 100) >= 10 && (n % 100) <= 20) cout << "The " << n << "th";
else
{
if ((n % 10) == 1) cout << "The " << n << "st";
else
{
if ((n % 10) == 2) cout << "The " << n << "nd";
else
{
if ((n % 10) == 3) cout << "The " << n << "rd";
else cout << "The " << n << "th";
}
}
}
cout << " humble number is " << humbleNumbers[n] << ".\n";
}
return 0;
}
2193



被折叠的 条评论
为什么被折叠?



