合并果子 加强版
题目链接:luogu P6033
题目大意
有一堆东西,每次你可以选两个东西,用它们大小的和的代价,把它们合并,得到一个它们大小和的东西。然后把它们合并成一个东西所要的最小的代价。
跟普通的一样,但是数据变大,O(nlogn) 无法通过。
思路
这里假设已经会普通的。
——>不会的点我<——
首先,我们看到数据很大,要用 O(n) 的算法。
然后我们考虑不用堆,而是用一些别的方法改进。
贪心还是用之前的贪心。
那问你就变成了如何一直维护一堆数中最小的两个数。
然后我们考虑先用一个方法把原序列排序,这里数据可以用桶排,如果数据大了也可以用基数排序。
然后我们再弄一个队列,记录新生成的数。
那很明显,新生成的数一定是从小到大的。
那我们就每次再两个队列的分别前两个数中(也就是那四个数中)选小的两个,然后弹出,在队列中插入新的值,记录花费。
然后这样做就可以了。
要开 long long,这很显然。
要开快读,这很显然。(然后我错了半天就是因为没开,搞得我还弄了个自带队列版)
代码
手动队列版
#include<queue>
#include<cstdio>
#define ll long long
using namespace std;
int n;
ll ans, x, y, xx, yy, box[100001];
ll q[10000001], p[10000001], t, tt;
int read() {
int re = 0;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9') {
re = re * 10 + c - '0';
c = getchar();
}
return re;
}
int main() {
n = read();
for (int i = 1; i <= n; i++) {
x = 1ll * read();
box[x]++;
}
for (int i = 1; i <= 100000; i++)
for (int j = 1; j <= box[i]; j++) {
q[++q[0]] = i;
}
while (p[0] + q[0] - t - tt > 1) {
x = q[t + 1];
xx = q[t + 2];
y = p[tt + 1];
yy = p[tt + 2];
if (xx < y && t + 2 <= q[0] || (tt + 1 > p[0])) y = xx, t += 2;
else if (yy < x && tt + 2 <= p[0] || (t + 1 > q[0])) x = yy, tt += 2;
else t++, tt++;
ans += x + y;
p[++p[0]] = x + y;
if (p[0] + q[0] - t - tt <= 1) {
break;
}
}
printf("%lld", ans);
return 0;
}
自带队列版
#include<queue>
#include<cstdio>
#define ll long long
using namespace std;
int n;
ll ans, x, y, xx, yy, box[200001];
queue <ll> q, p;
int read() {
int re = 0;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9') {
re = re * 10 + c - '0';
c = getchar();
}
return re;
}
int main() {
n = read();
for (int i = 1; i <= n; i++) {
x = 1ll * read();
box[x]++;
}
for (int i = 1; i <= 200000; i++)
for (int j = 1; j <= box[i]; j++) {
q.push(i);
}
while (1) {
x = 0;
y = 0;
if (q.empty() && p.empty()) break;
if (!q.empty()) xx = q.front();
else {
x = p.front();
p.pop();
if (!p.empty()) {
y = p.front();
p.pop();
}
else break;
}
if (!y) {
if (!p.empty()) yy = p.front();
else {
x = q.front();
q.pop();
if (!q.empty()) {
y = q.front();
q.pop();
}
else break;
}
}
if (!y) {
if (xx < yy) x = xx, q.pop();
else x = yy, p.pop();
if (q.empty() && p.empty()) break;
if (q.empty()) y = p.front(), p.pop();
else if (p.empty()) y = q.front(), q.pop();
else {
xx = p.front();
yy = q.front();
if (xx < yy) y = xx, p.pop();
else y = yy, q.pop();
}
}
ans += x + y;
p.push(x + y);
}
printf("%lld", ans);
return 0;
}