文章

454

粉丝

0

获赞

1

访问

9.7k

头像
栈 - thu 题解(四语言 AC 代码)
P5356 清华大学2024年机试题
发布于 2026年11月
阅读数 24

题意

n 个栈初始为空,支持三种操作:压入 c 个 w 并回答栈内元素和、从栈顶弹出 c 个并回答弹出元素和、把 x 栈整体翻转后并入 y 栈并回答 y 的和。

思路

  • 每个栈用一棵按位置维护的 treap,节点存值 w、重复个数 c、子树 size 与子树和,一个节点代表一段相同数值。

  • 压入即把新节点并到右端;弹出 c 个即按 size 分裂出右端 c 个并输出其和。

  • 整体翻转只需给根打 rev 懒标记,下推时交换左右儿子;合并两棵树等价于按 key 顺序合并两个 treap。

  • 和可能超过 32 位,统计量统一用 64 位。

复杂度

O(m log n),空间 O(m)。

参考代码(C / C++ / Java / Python)

C:

#include <stdio.h>
#include <stdlib.h>

struct N { long long w, cnt, sz, sum; int pr, l, r, rev; } t[500005];
int tot = 0;
unsigned int seed = 20240101u;

int rndint(void) {
    seed = seed * 1103515245u + 12345u;
    return (int)((seed >> 5) & 0x7fffffff);
}

int newnode(long long w, long long c) {
    ++tot;
    t[tot].w = w; t[tot].cnt = c; t[tot].sz = c; t[tot].sum = w * c;
    t[tot].pr = rndint(); t[tot].l = 0; t[tot].r = 0; t[tot].rev = 0;
    return tot;
}

void upd(int x) {
    if (!x) return;
    t[x].sz = t[t[x].l].sz + t[t[x].r].sz + t[x].cnt;
    t[x].sum = t[t[x].l].sum + t[t[x].r].sum + t[x].w * t[x].cnt;
}

void applyrev(int x) {
   ...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发