前の記事 (Link-Cut木と最遠点クエリ - ei1333の日記) の続き
SPOJにQTREE(Query on a tree)の問題群があります。
木に対するクエリの問題で、全部で7問あります。
これらは全部LCT(Link-Cut-Tree)を使って解くことができます。(QTREE LCTとかでぐぐると中国語でたくさんでてくる)
2019/07/17 更新 あとゆきこだの Dynamic Distance Sum もLCTを使って解けます。log^2 なんですが
はじめに
突然ですがLink-Cut-Treeって知っていますか? 僕は知っています(イキり)。知らない人は、がんばって
今回使ったLCTを以下に示しました。 部分木に対するクエリを処理できるように微妙に抽象化してあります。
template< typename SUM, typename KEY >
struct LinkCutTreeSubtree {
struct Node {
Node *l, *r, *p;
KEY key;
SUM sum;
bool rev;
int sz;
bool is_root() const {
return !p || (p->l != this && p->r != this);
}
Node(const KEY &key, const SUM &sum) :
key(key), sum(sum), rev(false), sz(1),
l(nullptr), r(nullptr), p(nullptr) {}
};
const SUM ident;
LinkCutTreeSubtree(const SUM &ident) : ident(ident) {}
Node *make_node(const KEY &key) {
auto ret = new Node(key, ident);
update(ret);
return ret;
}
Node *set_key(Node *t, const KEY &key) {
expose(t);
t->key = key;
update(t);
return t;
}
void toggle(Node *t) {
swap(t->l, t->r);
t->sum.toggle();
t->rev ^= true;
}
void push(Node *t) {
if(t->rev) {
if(t->l) toggle(t->l);
if(t->r) toggle(t->r);
t->rev = false;
}
}
void update(Node *t) {
t->sz = 1;
if(t->l) t->sz += t->l->sz;
if(t->r) t->sz += t->r->sz;
t->sum.merge(t->key, t->l ? t->l->sum : ident, t->r ? t->r->sum : ident);
}
void rotr(Node *t) {
auto *x = t->p, *y = x->p;
if((x->l = t->r)) t->r->p = x;
t->r = x, x->p = t;
update(x), update(t);
if((t->p = y)) {
if(y->l == x) y->l = t;
if(y->r == x) y->r = t;
update(y);
}
}
void rotl(Node *t) {
auto *x = t->p, *y = x->p;
if((x->r = t->l)) t->l->p = x;
t->l = x, x->p = t;
update(x), update(t);
if((t->p = y)) {
if(y->l == x) y->l = t;
if(y->r == x) y->r = t;
update(y);
}
}
void splay(Node *t) {
push(t);
while(!t->is_root()) {
auto *q = t->p;
if(q->is_root()) {
push(q), push(t);
if(q->l == t) rotr(t);
else rotl(t);
} else {
auto *r = q->p;
push(r), push(q), push(t);
if(r->l == q) {
if(q->l == t) rotr(q), rotr(t);
else rotl(t), rotr(t);
} else {
if(q->r == t) rotl(q), rotl(t);
else rotr(t), rotl(t);
}
}
}
}
Node *expose(Node *t) {
Node *rp = nullptr;
for(auto *cur = t; cur; cur = cur->p) {
splay(cur);
if(cur->r) cur->sum.add(cur->r->sum);
cur->r = rp;
if(cur->r) cur->sum.erase(cur->r->sum);
update(cur);
rp = cur;
}
splay(t);
return rp;
}
void link(Node *child, Node *parent) {
expose(child);
expose(parent);
child->p = parent;
parent->r = child;
}
void cut(Node *child) {
expose(child);
auto *parent = child->l;
child->l = nullptr;
parent->p = nullptr;
update(child);
}
void evert(Node *t) {
expose(t);
toggle(t);
push(t);
}
Node *lca(Node *u, Node *v) {
if(get_root(u) != get_root(v)) return nullptr;
expose(u);
return expose(v);
}
Node *get_kth(Node *x, int k) {
expose(x);
while(x) {
push(x);
if(x->r && x->r->sz > k) {
x = x->r;
} else {
if(x->r) k -= x->r->sz;
if(k == 0) return x;
k -= 1;
x = x->l;
}
}
return nullptr;
}
Node *get_root(Node *x) {
expose(x);
while(x->l) {
push(x);
x = x->l;
}
return x;
}
};
テンプレート引数でSUMとKEYの2つの型を渡す必要があります。SUM については次に挙げる
つのメンバ関数を実装する必要があります。
- toggle():= 左部分木と右部分木を入れ替える
- merge(key, parent, child):=左部分木 parent と右部分木childを現在の頂点の値 key を使ってマージする
- add(child):= 現在の頂点に Light-Edge で child を繋げる
- erase(child):= Light-Edgeで繋がっていた child を、現在の頂点から削除する
TODO 説明
QTREE
SPOJ.com - Problem QTREE
問題概要
辺に正の重みがついている. 以下のクエリを処理せよ.
- 辺
の重みを
に変更する
- 頂点
間の辺の重みのうち最大重みを求める
解法
evert(a) したあとに expose(b) をします。すると、
から
のパス上の頂点だけからなる
を根とする Splay 木ができます。
Splay木の各頂点には、max(左の子のmax, 右の子のmax, key) を持っておけばよいことがわかります(add()とかerase()とかはまだ関係ない)。
実装例
void beet() {
int N;
scanf("%d", &N);
struct Sum {
int max_cost;
Sum() : max_cost(-inf) {}
void toggle() {}
void merge(int cost, const Sum &parent, const Sum &child) {
max_cost = max({cost, parent.max_cost, child.max_cost});
}
void add(const Sum &chsum) {}
void erase(const Sum &chsum) {}
} e;
using LCT = LinkCutTreeSubtree< Sum, int >;
LCT lct(e);
vector< LCT::Node * > vv(N), ee(N);
for(int i = 0; i < N; i++) {
vv[i] = lct.make_node(0);
}
for(int i = 1; i < N; i++) {
int s, t, w;
scanf("%d %d %d", &s, &t, &w);
--s, --t;
lct.evert(vv[t]);
ee[i] = lct.make_node(w);
lct.link(vv[t], ee[i]);
lct.link(ee[i], vv[s]);
}
char buff[10];
while(true) {
scanf(" %s", buff);
if(buff[0] == 'D') break;
int x, y;
scanf("%d %d", &x, &y);
if(buff[0] == 'Q') {
--x, --y;
lct.evert(vv[x]);
lct.expose(vv[y]);
printf("%d\n", vv[y]->sum.max_cost);
} else if(buff[0] == 'C') {
lct.set_key(ee[x], y);
}
}
}
int main() {
int T;
scanf("%d", &T);
while(T--) beet();
}
QTREE2
SPOJ.com - Problem QTREE2
問題概要
辺に正の重みがついている. 以下のクエリを処理せよ.
- 頂点
間の距離を求める
- 頂点
から頂点
のパスで
番目に現れる頂点を求める
解法
さっきの問題と同様に、evert(a) したあとに expose(b) をします。すると、
から
のパス上の頂点だけからなる
を根とする Splay 木ができます。
距離クエリに答えるためにSplay木の各頂点には、左の子のsum+右の子のsum+keyを持っておけばよいことがわかります。
番目の頂点については、Splay木上を二分探索すると求めることが可能です。
実装例
void beet() {
int N;
scanf("%d", &N);
using pi = pair< int, int >;
struct Sum {
int cost;
Sum() : cost(0) {}
void toggle() {}
void merge(pi key, const Sum &parent, const Sum &child) {
cost = key.second + parent.cost + child.cost;
}
void add(const Sum &chsum) {}
void erase(const Sum &chsum) {}
} e;
using LCT = LinkCutTreeSubtree< Sum, pi >;
LCT lct(e);
vector< LCT::Node * > vv(N), ee(N);
for(int i = 0; i < N; i++) {
vv[i] = lct.make_node(pi(i + 1, 0));
}
for(int i = 1; i < N; i++) {
int s, t, w;
scanf("%d %d %d", &s, &t, &w);
--s, --t;
lct.evert(vv[t]);
ee[i] = lct.make_node(pi(-1, w));
lct.link(vv[t], ee[i]);
lct.link(ee[i], vv[s]);
}
char buff[10];
while(true) {
scanf(" %s", buff);
if(buff[1] == 'O') break;
int x, y;
scanf("%d %d", &x, &y);
--x, --y;
lct.evert(vv[y]);
lct.expose(vv[x]);
if(buff[0] == 'D') {
printf("%d\n", vv[x]->sum.cost);
} else if(buff[0] == 'K') {
int k;
scanf("%d", &k);
--k;
printf("%d\n", lct.get_kth(vv[x], 2 * k)->key.first);
}
}
}
int main() {
int T;
scanf("%d", &T);
while(T--) beet();
}
QTREE3
SPOJ.com - Problem QTREE3
問題概要
各頂点は白または黒の状態をとれて, 最初は全部白である. 以下のクエリを処理せよ.
- 頂点
の色を反転
- 頂点
から頂点
のパスで最初に現れる黒頂点を求める
実装例
これもさっきの問題と同様に、evert(1) したあとに expose(b) をします。すると、
から
のパス上の頂点だけからなる
を根とする Splay 木ができます。
(ホントは根は頂点
固定なので evert() しなくてもなんとかなるんですが、QTREE4以降がむずかしいので一応ここで) 今回の evert() では toggle() で何らかの処理が必要そうです。
Splay木の各頂点には、(もとの木で)もっとも浅い黒頂点の idx (l_idxとする) と(もとの木で)もっとも深い黒頂点の idx (r_idxとする) を持っておきます。Splay木上では浅い方の頂点はより左側に、深い方の頂点はより右側にあることになります。そのような頂点が存在しないとき、-1とします。
merge(key, parent, child)で、l_idx について考えます。まずparentのl_idxが-1でなければそれになります。-1かつkeyが-1ではなければkeyになって、keyもだめならchildのkeyになります。r_idxは逆に見ればよいです。
toggle() が来たら親(Splay木上での左部分木)と子(Splay木上での右部分木)が入れ替わるので swap(l_idx, r_idx) をすればよいです。
int main() {
int N, Q;
scanf("%d %d", &N, &Q);
struct Sum {
int l_idx, r_idx;
Sum() : l_idx(-1), r_idx(-1) {}
void toggle() {
swap(l_idx, r_idx);
}
void merge(int key, const Sum &parent, const Sum &child) {
l_idx = parent.l_idx;
if(l_idx == -1) l_idx = key;
if(l_idx == -1) l_idx = child.l_idx;
r_idx = child.r_idx;
if(r_idx == -1) r_idx = key;
if(r_idx == -1) r_idx = parent.r_idx;
}
void add(const Sum &chsum) {
}
void erase(const Sum &chsum) {
}
} e;
using LCT = LinkCutTreeSubtree< Sum, int >;
LCT lct(e);
vector< LCT::Node * > vv(N);
for(int i = 0; i < N; i++) {
vv[i] = lct.make_node(-1);
}
for(int i = 1; i < N; i++) {
int s, t;
scanf("%d %d", &s, &t);
--s, --t;
lct.evert(vv[t]);
lct.link(vv[t], vv[s]);
}
lct.evert(vv[0]);
while(Q--) {
int t, x;
scanf("%d %d", &t, &x);
--x;
if(t == 0) {
lct.set_key(vv[x], vv[x]->key == -1 ? x + 1 : -1);
} else if(t == 1) {
lct.expose(vv[x]);
printf("%d\n", vv[x]->sum.l_idx);
}
}
}
QTREE4
SPOJ.com - Problem QTREE4
問題概要
各頂点は白または黒の状態をとれて, 最初は全部白である. 辺に重みがついている. 重みは負もとりうる. 以下のクエリを処理せよ.
- 頂点
の色を反転
- すべての白同士の頂点ペア
のうち, 最大距離を求める
解法
特に全部白の場合について考えると木に対する直径クエリなので、それよりも難しそうです。また負の重みもあるのでうくちゃんです。
Splay木の各頂点
には、まずSplay木の部分木内で完結する直径のmax(diameterとする)が必要です。また部分木の重みの総和も欲しいです。
の親の更新を考えると、
の部分木のうちどこかの白頂点から
でSplay木の最も右の頂点に向かうパスの重みのmax(p_lenとする)と、Splay木の最も左の頂点から
の部分木のどこかの白頂点までのパスの重みのmax(c_lenとする)も欲しいです(ほしいので)。ここでparent.p_lenとchild.c_lenとkeyがあると、左部分木から
を通って右部分木に行くようなパスのうちmaxを得ることが可能です。
p_lenの更新は、max(child.p_len, parent.p_len+child.all) とすればよいです。前者は右部分木の結果で、後者は左部分木のどこかの頂点からchild.allを加算して一番右の頂点へ向かっています。c_lenでは逆をします。
また現在の頂点に Light-Edge で child を繋げたり切ったりするときに、child内の部分木で完結する直径のmaxとlight-edgeを(必ず)使って木を降りた時に可能なパスの重みのmaxも欲しいです。
えーこれらがあるとマージができるので勝ちます(コード見てね)。
直径は、
からのLight-Edgeを2本使うやつ(top + key + md1.top2())、左部分木のmax(parent.diameter)、右部分木のmax(child.diameter)、左部分木から
を通って
からの Light-Edge を使って終わるやつ、
からのLight-Edgeを使って
を通って右部分木へ向かうやつ、
からのLight-Edgeの直径のmax(md2.top()) とかを組み合わせるとできます。常に頂点
で直径の終端となれるとは限らない(白頂点のみ) (気づいたんですがカッコを多用しすぎじゃないか)ので、そのへんの場合分けをすると良いです。
実装例
時間制限があまりにも厳しすぎる う し た ぷ に き あ さ ん
Light-Edgeのうち最大値を管理するフェーズは、 priority_queue を 2 つ持って Light-Edgeの削除を遅延させることにすると定数倍が軽くてよさげ.
struct PQ {
priority_queue< int64 > in, out;
inline int64 top() {
if(!in.empty()) return in.top();
return -infll;
}
inline void insert(int64 k) {
if(k < -inf) return;
in.emplace(k);
}
inline void erase(int64 k) {
if(k < -inf) return;
out.emplace(k);
while(out.size() && in.top() == out.top()) {
in.pop();
out.pop();
}
}
inline int64 top2() {
if(in.empty()) return -infll;
int64 top = in.top();
erase(top);
int64 top2 = this->top();
in.push(top);
return top2;
}
};
int main() {
int N;
scanf("%d", &N);
using Key = int64;
struct Sum {
int64 all;
int64 p_len, c_len;
int64 diameter;
PQ md1, md2;
Sum() : all(0), p_len(-infll), c_len(-infll), diameter(-infll) {}
void toggle() {
swap(p_len, c_len);
}
void merge(Key key, const Sum &parent, const Sum &child) {
bool sw = false;
if(key == infll) {
sw = true;
key = 0;
}
all = parent.all + key + child.all;
int64 top = md1.top();
p_len = max(child.p_len, max(top, parent.p_len) + key + child.all);
c_len = max(parent.c_len, max(top, child.c_len) + key + parent.all);
diameter = max({parent.diameter, child.diameter, top + key + md1.top2(), md2.top()});
diameter = max({diameter, parent.p_len + key + max(child.c_len, top), child.c_len + key + top});
if(sw) {
p_len = max(p_len, key + child.all);
c_len = max(c_len, key + parent.all);
diameter = max(diameter, max({parent.p_len, child.c_len, top, 0LL}) + key);
}
if(p_len < -infll2) p_len = -infll;
if(c_len < -infll2) c_len = -infll;
if(diameter < -infll2) diameter = -infll;
}
void add(const Sum &ch) {
md1.insert(ch.c_len);
md2.insert(ch.diameter);
}
void erase(const Sum &ch) {
md1.erase(ch.c_len);
md2.erase(ch.diameter);
}
} e;
using LCT = LinkCutTreeSubtree< Sum, Key >;
LCT lct(e);
vector< LCT::Node * > vv(N), ee(N);
for(int i = 0; i < N; i++) {
vv[i] = lct.make_node(infll);
}
vector< pair< int, int > > g[100000];
for(int i = 1; i < N; i++) {
int s, t, w;
scanf("%d %d %d", &s, &t, &w);
--s, --t;
g[s].emplace_back(t, w);
g[t].emplace_back(s, w);
}
function< void(int, int) > dfs = [&](int idx, int par) {
for(auto &to : g[idx]) {
if(to.first == par) continue;
ee[to.first] = lct.make_node(to.second);
lct.link(vv[to.first], ee[to.first]);
lct.link(ee[to.first], vv[idx]);
dfs(to.first, idx);
}
};
dfs(0, -1);
int Q;
scanf("%d", &Q);
vector< char > T(Q);
vector< int > X(Q);
for(int i = 0; i < Q; i++) {
scanf(" %c", &T[i]);
if(T[i] == 'C') scanf("%d", &X[i]), --X[i];
}
lct.expose(vv[0]);
int64 last = vv[0]->sum.diameter;
for(int i = 0; i < Q; i++) {
if(T[i] == 'A') {
int64 ret = last;
if(ret < 0) puts("They have disappeared.\n");
else printf("%lld\n", ret);
} else {
lct.set_key(vv[X[i]], vv[X[i]]->key == infll ? 0 : infll);
last = vv[X[i]]->sum.diameter;
}
}
}
QTREE5
SPOJ.com - Problem QTREE5
問題概要
各頂点は白または黒の状態をとれて, 最初は全部黒である. 辺の重みはすべて1である. 以下のクエリを処理せよ.
- 頂点
の色を反転
- 頂点
から最も近い白頂点までの距離を求める
解法
QTREE4よりはちょっと簡単です。
Splay木の各頂点に、部分木内の頂点すべての重みの和(all)と、どこかから一番右の頂点へ向かうパスのmin(p_len)と一番左の頂点からどこかへ向かうパスのmin(c_len)を持ってやります。
実装例
struct PQ {
priority_queue< int, vector< int >, greater< int > > in, out;
inline int top() {
if(!in.empty()) return in.top();
return inf;
}
inline void insert(int k) {
in.emplace(k);
}
inline void erase(int k) {
out.emplace(k);
while(out.size() && in.top() == out.top()) {
in.pop();
out.pop();
}
}
};
int main() {
int N;
scanf("%d", &N);
struct Sum {
int all;
int p_len, c_len;
PQ md1;
Sum() : all(0), p_len(inf), c_len(inf) {}
void toggle() {
swap(p_len, c_len);
}
void merge(bool iswhite, const Sum &parent, const Sum &child) {
all = parent.all + 1 + child.all;
int top = md1.top();
p_len = min(child.p_len, min(top, parent.p_len) + 1 + child.all);
c_len = min(parent.c_len, min(top, child.c_len) + 1 + parent.all);
if(iswhite) {
p_len = min(p_len, 1 + child.all);
c_len = min(c_len, 1 + parent.all);
}
}
void add(const Sum &ch) {
md1.insert(ch.c_len);
}
void erase(const Sum &ch) {
md1.erase(ch.c_len);
}
} e;
using LCT = LinkCutTreeSubtree< Sum, bool >;
LCT lct(e);
vector< LCT::Node * > vv(N);
for(int i = 0; i < N; i++) {
vv[i] = lct.make_node(false);
}
vector< int > g[100000];
for(int i = 1; i < N; i++) {
int s, t;
scanf("%d %d", &s, &t);
--s, --t;
g[s].emplace_back(t);
g[t].emplace_back(s);
}
function< void(int, int) > dfs = [&](int idx, int par) {
for(auto &to : g[idx]) {
if(to == par) continue;
lct.link(vv[to], vv[idx]);
dfs(to, idx);
}
};
dfs(0, -1);
int Q;
scanf("%d", &Q);
vector< int > T(Q), X(Q);
for(int i = 0; i < Q; i++) {
scanf("%d %d", &T[i], &X[i]);
--X[i];
}
for(int i = 0; i < Q; i++) {
if(T[i] == 1) {
lct.evert(vv[X[i]]);
auto ret = vv[X[i]]->sum.c_len;
if(ret >= inf) ret = 0;
printf("%d\n", ret - 1);
} else {
lct.set_key(vv[X[i]], vv[X[i]]->key ^ 1);
}
}
}
QTREE6
SPOJ.com - Problem QTREE6
問題概要
各頂点は白または黒の状態をとれて, 最初は全部黒である. 以下のクエリを処理せよ.
- 頂点
が所属する連結成分に含まれる頂点の個数を求める.
と
のパス上のすべての頂点がすべて同じ色なら, 同じ連結成分に所属する.
- 頂点
の色を反転
解法
同じ色の連結成分だけからなる木を取得できれば、あとは適当に頂点数を求めるだけなので勝ちます。
普通にやるとたぶんできないんですが、頭いいことをするとできます。
疲れたので解説をこどふぉに投げるんですが、Codeforces Round #564 Editorial - CodeforcesのEのTutorialの図を見てみましょう。
黒のみからなる連結成分に加えて、その親に白色の頂点を
個加えた木を持っています。特に白色の頂点は根です。このように管理することで、linkとcutが効率的にできます。ある頂点が白から黒になったときその頂点を親と繋ぐ(link)、ある頂点が黒から白になったときその頂点を親から切り離す(cut)をすればよいです。
連結成分の個数クエリを処理することを考えます。頂点
が今黒色だとするとこの木の根は白色です。白色を挟んで別の黒色の連結成分が繋がっている可能性があるので困ります。
expose(
) をすることで白色の頂点から
までのパス上の頂点からなるSplay木を得ることができます。このSplay木の
番左の頂点が白色の頂点です。
番目の頂点は、(もともとの木で)白色の頂点を直接指す黒色の頂点のハズです。
このへん
auto p = white[x] ? v_w[x] : v_b[x];
lct.expose(p);
auto q = lct.get_kth(p, p->sz - 2);
auto r = lct.get_root(p);
lct.cut(q);
この頂点を探して(log nとかで探せる)cutすると求めたい連結成分のみからなるSplay木を得ることができます。
実装例
int main() {
int N;
scanf("%d", &N);
struct Sum {
int comp, md;
Sum() : comp(0), md(0) {}
void toggle() {}
void merge(int key, const Sum &parent, const Sum &child) {
comp = key;
comp += parent.comp;
comp += child.comp;
comp += md;
}
void add(const Sum &chsum) {
md += chsum.comp;
}
void erase(const Sum &chsum) {
md -= chsum.comp;
}
} e;
using LCT = LinkCutTreeSubtree< Sum, int >;
LCT lct(e);
vector< LCT::Node * > v_w(N + 1), v_b(N + 1);
vector< vector< int > > g(N + 1);
vector< int > white(N);
for(int i = 0; i <= N; i++) {
v_w[i] = lct.make_node(1);
v_b[i] = lct.make_node(1);
}
for(int i = 1; i < N; i++) {
int s, t;
scanf("%d %d", &s, &t);
--s, --t;
g[s].emplace_back(t);
g[t].emplace_back(s);
}
g[N].emplace_back(0);
vector< int > par(N);
function< void(int, int) > dfs = [&](int idx, int p) {
for(auto to : g[idx]) {
if(to == p) continue;
lct.link(v_b[to], v_b[idx]);
par[to] = idx;
dfs(to, idx);
}
};
dfs(N, -1);
int Q;
scanf("%d", &Q);
while(Q--) {
int t, x;
scanf("%d %d", &t, &x);
--x;
if(t == 0) {
auto p = white[x] ? v_w[x] : v_b[x];
lct.expose(p);
auto q = lct.get_kth(p, p->sz - 2);
auto r = lct.get_root(p);
lct.cut(q);
printf("%d\n", q->sum.comp);
lct.link(q, r);
} else {
if(white[x]) {
lct.cut(v_w[x]);
lct.link(v_b[x], v_b[par[x]]);
} else {
lct.cut(v_b[x]);
lct.link(v_w[x], v_w[par[x]]);
}
white[x] ^= 1;
}
}
}
QTREE7
SPOJ.com - Problem QTREE7
問題概要
各頂点は白または黒の状態をとれ, 最初は全部黒である. また, 頂点には重みが割り当てられている. 以下のクエリを処理せよ.
- 頂点
が所属する連結成分の頂点のうち, 最大重みを求める.
と
のパス上のすべての頂点がすべて同じ色なら, 同じ連結成分に所属する.
- 頂点
の色を反転
- 頂点
の重みを
に変更
解法
QTREE6とほとんど同じ
実装例
struct PQ {
priority_queue< int > in, out;
inline int top() {
if(!in.empty()) return in.top();
return -inf;
}
inline void insert(int k) {
in.emplace(k);
}
inline void erase(int k) {
out.emplace(k);
while(out.size() && in.top() == out.top()) {
in.pop();
out.pop();
}
}
};
int main() {
int N;
scanf("%d", &N);
struct Sum {
int mx;
PQ pq;
Sum() : mx(-inf) {}
void toggle() {}
void merge(int key, const Sum &parent, const Sum &child) {
mx = max({key, parent.mx, child.mx, pq.top()});
}
void add(const Sum &chsum) {
pq.insert(chsum.mx);
}
void erase(const Sum &chsum) {
pq.erase(chsum.mx);
}
} e;
using LCT = LinkCutTreeSubtree< Sum, int >;
LCT lct(e);
vector< LCT::Node * > v_w(N + 1), v_b(N + 1);
vector< vector< int > > g(N + 1);
vector< int > white(N), w(N, -inf);
for(int i = 1; i < N; i++) {
int s, t;
scanf("%d %d", &s, &t);
--s, --t;
g[s].emplace_back(t);
g[t].emplace_back(s);
}
g[N].emplace_back(0);
for(int i = 0; i < N; i++) {
scanf("%d", &white[i]);
}
for(int i = 0; i < N; i++) {
scanf("%d", &w[i]);
}
for(int i = 0; i <= N; i++) {
v_w[i] = lct.make_node(w[i]);
v_b[i] = lct.make_node(w[i]);
}
vector< int > par(N);
function< void(int, int) > dfs = [&](int idx, int p) {
for(auto to : g[idx]) {
if(to == p) continue;
if(white[to]) lct.link(v_w[to], v_w[idx]);
else lct.link(v_b[to], v_b[idx]);
par[to] = idx;
dfs(to, idx);
}
};
dfs(N, -1);
int Q;
scanf("%d", &Q);
while(Q--) {
int t, x;
scanf("%d %d", &t, &x);
--x;
if(t == 0) {
auto p = white[x] ? v_w[x] : v_b[x];
lct.expose(p);
auto q = lct.get_kth(p, p->sz - 2);
auto r = lct.get_root(p);
lct.cut(q);
printf("%d\n", q->sum.mx);
lct.link(q, r);
} else if(t == 1) {
if(white[x]) {
lct.cut(v_w[x]);
lct.link(v_b[x], v_b[par[x]]);
} else {
lct.cut(v_b[x]);
lct.link(v_w[x], v_w[par[x]]);
}
white[x] ^= 1;
} else {
int y;
scanf("%d", &y);
lct.set_key(v_b[x], y);
lct.set_key(v_w[x], y);
}
}
}
Dynamic Distance Sum
No.772 Dynamic Distance Sum - yukicoder
解法
値が1の頂点までの距離の総和は, 1の頂点数と距離を持っておけば比較的容易にできる.
Light-edgeを考慮しない場合, 適当な頂点でexpose()してsplay木上を探索するとなんかできる. 具体的には, 1の頂点数が過半数を超える子に潜る操作をシミュレーションすればよい. まず子(右部分木)をみて, 自分を見て, それでもダメなら親(左部分木)に移動すれば良い. 自分および親に移動するときには, 子の部分木の1の頂点数を足し込みたい気持ちになるので, 再帰の引数でどれだけたされたかを持っておく必要がある.
実はLight-edgeにも潜ることができる. multisetでLight-edgeでつながるそれぞれのSplay全体の1の頂点数を管理しておき, 可能性があるのは頂点数が最大のものなのでこれはすぐ求まる. Light-edgeがSplay木のどこに繋がっているかについてはSplay木の根へのポインタを持っていれば良いが注意が必要. 下のSplay木からsplay()したときにその木の根がこわれるので破滅する. これはLight-edgeに番号を振っておくことで対処できて, Splay木の根が変わったときにはLight-edgeの番号を参照して更新してあげれば良い.
controlをLight-edgeの番号と根を結びつける配列として, splayしてtを根にする前に以下の処理を挟む.
Node *rot = t;
while(!rot->is_root()) rot = rot->p;
t->belong = rot->belong;
if(~t->belong) control[t->belong] = t;
新しくLight-edgeを生やす操作は以下のような感じ. curとcur->rをLight-edgeで繋ぐ.
cur->r->belong = (int) control.size();
control.emplace_back(cur->r);
cur->sum.add(cur->r->sum, cur->r->belong);
#include <bits/stdc++.h>
using namespace std;
using int64 = long long;
const int mod = 998244353;
const int64 infll = (1LL << 60) - 1;
const int inf = (1 << 30) - 1;
struct IoSetup {
IoSetup() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
cerr << fixed << setprecision(10);
}
} iosetup;
template< typename T1, typename T2 >
ostream &operator<<(ostream &os, const pair< T1, T2 > &p) {
os << p.first << " " << p.second;
return os;
}
template< typename T1, typename T2 >
istream &operator>>(istream &is, pair< T1, T2 > &p) {
is >> p.first >> p.second;
return is;
}
template< typename T >
ostream &operator<<(ostream &os, const vector< T > &v) {
for(int i = 0; i < (int) v.size(); i++) {
os << v[i] << (i + 1 != v.size() ? " " : "");
}
return os;
}
template< typename T >
istream &operator>>(istream &is, vector< T > &v) {
for(T &in : v) is >> in;
return is;
}
template< typename T1, typename T2 >
inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }
template< typename T1, typename T2 >
inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }
template< typename T = int64 >
vector< T > make_v(size_t a) {
return vector< T >(a);
}
template< typename T, typename... Ts >
auto make_v(size_t a, Ts... ts) {
return vector< decltype(make_v< T >(ts...)) >(a, make_v< T >(ts...));
}
template< typename T, typename V >
typename enable_if< is_class< T >::value == 0 >::type fill_v(T &t, const V &v) {
t = v;
}
template< typename T, typename V >
typename enable_if< is_class< T >::value != 0 >::type fill_v(T &t, const V &v) {
for(auto &e : t) fill_v(e, v);
}
template< typename F >
struct FixPoint : F {
FixPoint(F &&f) : F(forward< F >(f)) {}
template< typename... Args >
decltype(auto) operator()(Args &&... args) const {
return F::operator()(*this, forward< Args >(args)...);
}
};
template< typename F >
inline decltype(auto) MFP(F &&f) {
return FixPoint< F >{forward< F >(f)};
}
template< typename SUM, typename KEY >
struct LinkCutTreeSubtree {
struct Node {
Node *l, *r, *p;
int belong;
KEY key;
SUM sum;
bool rev;
int sz;
bool is_root() const {
return !p || (p->l != this && p->r != this);
}
Node(const KEY &key, const SUM &sum) :
key(key), sum(sum), rev(false), sz(1), belong(-1),
l(nullptr), r(nullptr), p(nullptr) {}
};
struct Edge {
Node *p, *q;
Edge(Node *p, Node *q) : p(p), q(q) {}
};
const SUM ident;
vector< Node * > control;
LinkCutTreeSubtree(const SUM &ident) : ident(ident) {}
Node *make_node(const KEY &key) {
auto ret = new Node(key, ident);
update(ret);
return ret;
}
Node *set_key(Node *t, const KEY &key) {
expose(t);
t->key = key;
update(t);
return t;
}
void toggle(Node *t) {
swap(t->l, t->r);
t->sum.toggle();
t->rev ^= true;
}
void push(Node *t) {
if(t->rev) {
if(t->l) toggle(t->l);
if(t->r) toggle(t->r);
t->rev = false;
}
}
void update(Node *t) {
t->sz = 1;
if(t->l) t->sz += t->l->sz;
if(t->r) t->sz += t->r->sz;
t->sum.merge(t->key, t->l ? t->l->sum : ident, t->r ? t->r->sum : ident);
}
void rotr(Node *t) {
auto *x = t->p, *y = x->p;
if((x->l = t->r)) t->r->p = x;
t->r = x, x->p = t;
update(x), update(t);
if((t->p = y)) {
if(y->l == x) y->l = t;
if(y->r == x) y->r = t;
update(y);
}
}
void rotl(Node *t) {
auto *x = t->p, *y = x->p;
if((x->r = t->l)) t->l->p = x;
t->l = x, x->p = t;
update(x), update(t);
if((t->p = y)) {
if(y->l == x) y->l = t;
if(y->r == x) y->r = t;
update(y);
}
}
void splay(Node *t) {
push(t);
Node *rot = t;
while(!rot->is_root()) rot = rot->p;
t->belong = rot->belong;
if(~t->belong) control[t->belong] = t;
while(!t->is_root()) {
auto *q = t->p;
if(q->is_root()) {
push(q), push(t);
if(q->l == t) rotr(t);
else rotl(t);
} else {
auto *r = q->p;
push(r), push(q), push(t);
if(r->l == q) {
if(q->l == t) rotr(q), rotr(t);
else rotl(t), rotr(t);
} else {
if(q->r == t) rotl(q), rotl(t);
else rotr(t), rotl(t);
}
}
}
}
Node *expose(Node *t) {
Node *rp = nullptr;
for(auto *cur = t; cur; cur = cur->p) {
splay(cur);
if(cur->r) {
cur->r->belong = (int) control.size();
control.emplace_back(cur->r);
cur->sum.add(cur->r->sum, cur->r->belong);
}
cur->r = rp;
if(cur->r) {
cur->sum.erase(cur->r->sum, cur->r->belong);
}
update(cur);
rp = cur;
}
splay(t);
return rp;
}
void link(Node *child, Node *parent) {
expose(child);
expose(parent);
child->p = parent;
parent->r = child;
update(parent);
}
void cut(Node *child) {
expose(child);
auto *parent = child->l;
child->l = nullptr;
parent->p = nullptr;
update(child);
}
void evert(Node *t) {
expose(t);
toggle(t);
push(t);
}
Node *lca(Node *u, Node *v) {
if(get_root(u) != get_root(v)) return nullptr;
expose(u);
return expose(v);
}
Node *get_kth(Node *x, int k) {
expose(x);
while(x) {
push(x);
if(x->r && x->r->sz > k) {
x = x->r;
} else {
if(x->r) k -= x->r->sz;
if(k == 0) return x;
k -= 1;
x = x->l;
}
}
return nullptr;
}
Node *get_root(Node *x) {
expose(x);
while(x->l) {
push(x);
x = x->l;
}
return x;
}
};
template< typename T, typename Compare = less< T > >
struct PQ {
priority_queue< T, vector< T >, Compare > que1, que2;
PQ() = default;
void push(T k) {
que1.emplace(k);
}
void pop(T k) {
que2.emplace(k);
}
inline void modify() {
while(que2.size() && que2.top() == que1.top()) {
que2.pop();
que1.pop();
}
}
bool empty() {
modify();
return que1.empty();
}
T top() {
modify();
return que1.top();
}
};
int main() {
struct Sum {
int64 all, pdist, cdist, sz, mdist, msz;
PQ< pair< int64, int > > pq;
Sum() : all(0), pdist(0), cdist(0), sz(0), mdist(0), msz(0) {}
void toggle() {
swap(pdist, cdist);
}
void merge(int key, const Sum &parent, const Sum &child) {
bool sw = false;
if(key == -1) {
key = 0;
sw = true;
}
all = parent.all + key + child.all;
pdist = parent.pdist + (key + child.all) * (parent.sz + sw + msz) + child.pdist + mdist;
cdist = child.cdist + (key + parent.all) * (child.sz + sw + msz) + parent.cdist + mdist;
sz = parent.sz + child.sz + msz + sw;
}
void add(const Sum &chsum, int id) {
mdist += chsum.cdist;
msz += chsum.sz;
pq.push({chsum.sz, id});
}
void erase(const Sum &chsum, int id) {
mdist -= chsum.cdist;
msz -= chsum.sz;
pq.pop({chsum.sz, id});
}
} e;
using LCT = LinkCutTreeSubtree< Sum, int >;
LCT lct(e);
int N, Q;
cin >> N >> Q;
vector< LCT::Node * > vv(N), ee(Q);
auto search = MFP([&](auto search, LCT::Node *t, int half, int pre) -> LCT::Node * {
lct.push(t);
int r = t->r ? t->r->sum.sz : 0;
if(t->r && half <= pre + r) return search(t->r, half, pre);
if(!t->sum.pq.empty()) {
auto ret = t->sum.pq.top();
if(half <= ret.first) return search(lct.control[ret.second], half, 0);
}
int cur = (t->key == -1) + t->sum.msz + r + pre;
if(half <= cur) return t;
return search(t->l, half, cur);
});
int ptr = 0;
for(int i = 0; i < N; i++) {
vv[i] = lct.make_node(-1);
}
int64 S = 0;
map< pair< int, int >, int > ex;
for(int i = 0; i < Q; i++) {
int64 T, A, B, C;
cin >> T >> A;
A = (A - 1 + S) % N;
if(T == 1) {
cin >> B >> C;
B = (B - 1 + S) % N;
ee[ptr] = lct.make_node(C);
lct.evert(vv[B]);
lct.link(vv[B], ee[ptr]);
lct.link(ee[ptr], vv[A]);
ex[minmax(A, B)] = ptr++;
} else if(T == 2) {
cin >> B;
B = (B - 1 + S) % N;
lct.evert(vv[A]);
auto it = ex.find(minmax(A, B));
lct.cut(ee[it->second]);
lct.evert(ee[it->second]);
ex.erase(it);
lct.cut(vv[B]);
} else {
lct.set_key(vv[A], vv[A]->key == -1 ? 0 : -1);
if(vv[A]->sum.sz <= 1) {
cout << 0 << "\n";
} else {
auto root = search(vv[A], (vv[A]->sum.sz - 1) / 2 + 1, 0);
lct.evert(root);
S += root->sum.cdist;
S %= N;
cout << root->sum.cdist << "\n";
}
}
}
}
さいごに
いやこのせつめいみてもわかんなくない?(本末転倒)
たぴちゃんたべてやる