4kyu Twice linear
题目背景:
Task
Consider a sequence u where u is defined as follows:
1. The number u(0) = 1 is the first one in u.
2. For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.
3. There are no other numbers in u.
Given parameter n the function dbl_linear (or dblLinear…) returns the element u(n) of the ordered (with <) sequence u (so, there are no duplicates).
Example
u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]
dbl_linear(10) should return 22
题目分析:
本道题目的思路很清晰,就是不断迭代数组中的元素,以及该元素 u 的 2 * u + 1 和 3 * u + 1,我们需要做的是如何把这些元素按照从小到大的顺序排序。简单的思路就是借用队列去维护 2 * u + 1,及 3 * u + 1 的非记录元素,每个队列里面的数据是从小到大的排序,每一次都是比对两个队列的队首元素,然后次数 +1。
AC代码:
#include <queue>
class DoubleLinear
{
public:
static int dblLinear(int n);
};
int DoubleLinear::dblLinear(int n) {
std::queue<int> q2;
std::queue<int> q3;
int tmp = 1, cnt = 0;
while( cnt != n ) {
q2.push(tmp * 2 + 1);
q3.push(tmp * 3 + 1);
if ( q2.front() < q3.front() ) {
tmp = q2.front();
q2.pop();
}
else if ( q2.front() > q3.front() ) {
tmp = q3.front();
q3.pop();
}
else {
tmp = q2.front();
q2.pop();
q3.pop();
}
cnt++;
}
return tmp;
}