题意:自行脑补。
Sol:一种显然的方法就是拿堆维护前n小元素,时间复杂度O(nlogn).不过这样会超时。
事实上由于两个函数都是单调递增的,我们用两个指针在同一个序列中进行线性合并并添加元素,不难证明时间复杂度为O(n).
Code:
Heap O(nlogn)
#include <cstdio>
#include <cstring>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <functional>
using namespace std;
typedef unsigned long long LU;
struct Case {
LU x;
Case(LU _x = 0):x(_x){}
bool operator > (const Case &B) const {
return x < B.x;
}
bool operator < (const Case &B) const {
return x > B.x;
}
};
priority_queue<Case> q;
int main() {
int c, N;
scanf("%d%d", &c, &N);
register int i, j;
int a1, b1, d1;
scanf("%d%d%d", &a1, &b1, &d1);
int a2, b2, d2;
scanf("%d%d%d", &a2, &b2, &d2);
q.push(Case(c));
LU x, last = 0;
for(i = 1; i <= N;) {
x = q.top().x;
q.pop();
if (x != last) {
q.push(Case(x * a1 / (LU)d1 + (LU)b1));
q.push(Case(x * a2 / (LU)d2 + (LU)b2));
last = x;
if (i == N)
printf("%llu", x);
++i;
}
}
return 0;
}
Merge Sort O(n)
#include <cstdio>
#include <cstring>
#include <climits>
#include <algorithm>
#include <iostream>
using namespace std;
typedef unsigned long long LU;
LU seq[4000010];
int main() {
int c, N;
scanf("%d%d", &c, &N);
register int i, j;
int a1, b1, d1;
scanf("%d%d%d", &a1, &b1, &d1);
int a2, b2, d2;
scanf("%d%d%d", &a2, &b2, &d2);
seq[1] = c;
int p1 = 1, p2 = 1;
LU nxt1 = seq[1] * a1 / d1 + b1;
LU nxt2 = seq[1] * a2 / d2 + b2;
for(i = 2; i <= N; ) {
if (nxt1 < nxt2) {
if (nxt1 != seq[i - 1])
seq[i++] = nxt1;
nxt1 = seq[++p1] * a1 / d1 + b1;
}
else {
if (nxt2 != seq[i - 1])
seq[i++] = nxt2;
nxt2 = seq[++p2] * a2 / d2 + b2;
}
}
printf("%llu", seq[N]);
return 0;
}