[P3273 / SCOI2011] 棘手的操作 题解

· · 题解

看一眼标签和题解,啊,全是可删堆

我们考虑用启发式合并和 (multi)set,先用一个并查集维护连通性,接着用一个 set 记录每个块的最大值,用 multiset 记录全局最大值,再用 v_i 记录每个块要加的值。(注意,真正的 a_i 的值是 a_i+v_i)

设 getf(x) 指的是 x 所在块的根。

U

将 x,y 连起来。

我们假设 f_i 是并查集数组,如果是根,就是负的 sz_i 值,按大小合并 x 所在的块和 y 所在的块,并更新在 y 中的 a_i。

具体来说,假设 x 大,y 小,将 y 中的所有元素 a_i 加上 v_y-v_x 而 v_x 不变。

cin >> x >> y;
x = getf(x);
y = getf(y);
if (x == y) continue;
if (s[x].size() < s[y].size()) swap(x, y);
if (!s[x].empty()&&gm.find((*s[x].begin()).first + v[x])!=gm.end()) gm.erase(gm.find((*s[x].begin()).first + v[x]));
if (!s[y].empty()&&gm.find((*s[y].begin()).first + v[y])!=gm.end()) gm.erase(gm.find((*s[y].begin()).first + v[y]));
for (auto it : s[y]) {
    a[it.second] = it.first + v[y] - v[x];
    s[x].insert({a[it.second], it.second});
}
s[y].clear();
f[x] += f[y];
f[y] = x;
if (!s[x].empty()) gm.insert((*s[x].begin()).first + v[x]);

A1

我们先把 set 和 multiset 里的值删除,然后改变 a_x,最后将 a_x 加入。

cin >> x >> y;                                                
int rt = getf(x);                                             
if (!s[rt].empty()) gm.erase((*s[rt].begin()).first + v[rt]); 
s[rt].erase({a[x], x});                                       
a[x] += y;                                                    
s[rt].insert({a[x], x});                                      
if (!s[rt].empty()) gm.insert((*s[rt].begin()).first + v[rt]);

A2

我们只需将这个连通块的最大元素在 multiset 里改过来,在修改 v_x 的值。

int rt = getf(x);
if (!s[rt].empty()) gm.erase((*s[rt].begin()).first + v[rt]);
v[rt] += y;
if (!s[rt].empty()) gm.insert((*s[rt].begin()).first + v[rt]);

A3

只需修改整体标记。

cin>>y;
u+=y;

F1

由于真实的 a_x 是 a_x+v_{getf(x)}+u,所以输出。

cin >> x;
cout << a[x] + v[getf(x)] + u << "\n";

F2

我们寻找根为 getf(x) 的块,如果为空输出 v_{getf(x)}+u,否则输出块中的最大值加上 v_{getf(x)}+u。

cin >> x;
int rt = getf(x);
if (s[rt].empty()) {
    cout << v[rt] + u << "\n";
} else {
    cout << (*s[rt].begin()).first + v[rt] + u << "\n";
}

F3

如果 multiset 为空,输出 u,否则输出 multiset 的最大值加上 u。

if (gm.empty()) {
    cout << u << "\n";
} else {
    cout << (*gm.begin()) + u << "\n";
}

简单吧(写了 2h)。