4kyu Twice linear
生活随笔
收集整理的這篇文章主要介紹了
4kyu Twice linear
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
4kyu Twice linear
題目背景:
Task
Consider a sequence u where u is defined as follows:
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題目分析:
本道題目的思路很清晰,就是不斷迭代數(shù)組中的元素,以及該元素 u 的 2 * u + 1 和 3 * u + 1,我們需要做的是如何把這些元素按照從小到大的順序排序。簡(jiǎn)單的思路就是借用隊(duì)列去維護(hù) 2 * u + 1,及 3 * u + 1 的非記錄元素,每個(gè)隊(duì)列里面的數(shù)據(jù)是從小到大的排序,每一次都是比對(duì)兩個(gè)隊(duì)列的隊(duì)首元素,然后次數(shù) +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; }總結(jié)
以上是生活随笔為你收集整理的4kyu Twice linear的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 4kyu Sums of Perfect
- 下一篇: 4kyu N linear