题面
来源:USACO 官网。模型收到的是同一份题面的文字。
There are $N$ ($1\le N\le 2\cdot 10^5$) cows labeled $1\dots N$ on Farmer John's farm, where each cow lives in its own barn. Each cow $i$ has a best friend $a_i$ ($1\le a_i\le N$). Cows can be best friends with themselves, and multiple cows can have the same best friend. The cows love to party, so they have decided to throw a party for $M$ ($1\le M\le 2\cdot 10^5$) consecutive nights.
On night $i$, cow $c_i$ will decide to throw a party of type $t_i$ at its barn, where $t_i\in \texttt{"COW"}$. This party will exist for all future nights as well, until cow $c_i$ decides to throw a party of a different type.
Every night, each cow will attempt to go to a party. If a cow is not hosting a party, they will check their best friend's barn, and if there is no party there, will follow their best friend to wherever they are going (who might also follow their best friend and so on). It is possible that a cow might never find a party and will then give up for the night.
Compute for each night, the number of cows that end up at a party of type $C$, $O$, and $W$ respectively.
INPUT FORMAT (input arrives from the terminal / stdin):
The first line contains $N$, the number of cows.The second line contains $a_1,\dots, a_N$, where $a_i$ is cow $i$'s best friend.
The third line contains $M$, the number of nights.
The next $M$ lines each contain an integer $c_i$ ($1\le c_i\le N$) and a character $v_i$, representing the cow that is throwing the party and the party type respectively.
OUTPUT FORMAT (print output to the terminal / stdout):
Output $M$ lines, where the $i$th consists of $3$ space-separated integers, the number of cows going to parties of type $C$, $O$, and $W$ on the $i$th night, respectively.SAMPLE INPUT:
5 2 3 4 5 4 4 2 C 4 C 4 W 2 O
SAMPLE OUTPUT:
2 0 0 5 0 0 2 0 3 0 2 3
On night $1$, there is only one party of type $C$ at barn $2$, which only cows $1$ and $2$ attend.
On night $2$, there is a new party of type $C$ at barn $4$, which cows $3$, $4$, and $5$ can now reach.
On night $3$, the party at barn $4$ is changed to type $W$, affecting cows $3$, $4$ and $5$.
On night $4$, the party at barn $2$ is changed to type $O$, affecting cows $1$ and $2$.
SCORING:
- Input 2: $N, M\leq 100$
- Inputs 3-4: $N, M\leq 4000$
- Inputs 5-9: $\{a_i\}$ is a permutation of $\{1,\dots, N\}$
- Inputs 10-21: No additional constraints
Problem credits: Benjamin Qi
结果
Kimi K3.1 ProKimi
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 20.1k平均输出 token(含思考) ↓
- 24.1输出速度 tokens/s ↑
- 798 秒延迟 ↓
- 1.82×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
DeepSeek Flash V4.1-1017DeepSeek
2/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 9.5采样 3 · 答案错误
- 40.7k平均输出 token(含思考) ↓
- 197.5输出速度 tokens/s ↑
- 209 秒延迟 ↓
- 1.07×CPU 时间 / 官方解 ↓
- 同阶 2时间复杂度(相对官方解)
MiniMax M3.1 FlashMiniMax
2/3
解出的采样 ↑
- 14.3采样 1 · 答案错误
- 100采样 2 · 解出
- 100采样 3 · 解出
- 60.6k平均输出 token(含思考) ↓
- 135.3输出速度 tokens/s ↑
- 388 秒延迟 ↓
- 1.19×CPU 时间 / 官方解 ↓
- 同阶 2时间复杂度(相对官方解)
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
#include <bits/stdc++.h> using namespace std; struct Fenwick { int n = 0; vector<long long> bit; Fenwick() {} explicit Fenwick(int n_) { init(n_); } void init(int n_) { n = n_; bit.assign(n + 1, 0); } void add(int i, long long v) { for (; i <= n; i += i & -i) bit[i] += v; } long long sum(int i) const { long long res = 0; for (; i > 0; i -= i & -i) res += bit[i]; return res; } // Range addition, point queries. void rangeAdd(int l, int r, long long v) { if (l > r) return; add(l, v); if (r + 1 <= n) add(r + 1, -v); } long long pointQuery(int i) const { return sum(i); } }; struct CycleComponent { vector<int> nodes; int offset = 0; set<int> parties; // Local positions on the cycle. }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N + 1); for (int i = 1; i <= N; i++) cin >> a[i]; int M; cin >> M; // Remove non-cycle vertices using in-degree peeling. vector<int> deg(N + 1, 0); for (int i = 1; i <= N; i++) deg[a[i]]++; queue<int> q; for (int i = 1; i <= N; i++) { if (deg[i] == 0) q.push(i); } while (!q.empty()) { int v = q.front(); q.pop(); if (--deg[a[v]] == 0) q.push(a[v]); } vector<char> isCycle(N + 1, false); for (int i = 1; i <= N; i++) { if (deg[i] > 0) isCycle[i] = true; } vector<CycleComponent> comps; vector<int> compOf(N + 1, -1), cyclePos(N + 1, -1); vector<char> seen(N + 1, false); vector<int> roots; int totalCycleVertices = 0; for (int i = 1; i <= N; i++) { if (!isCycle[i] || seen[i]) continue; int id = (int)comps.size(); CycleComponent comp; comp.offset = totalCycleVertices; int v = i, p = 0; do { seen[v] = true; compOf[v] = id; cyclePos[v] = p++; comp.nodes.push_back(v); roots.push_back(v); v = a[v]; } while (v != i); totalCycleVertices += p; comps.push_back(std::move(comp)); } // Each cycle vertex roots a tree directed towards that cycle vertex. vector<vector<int>> children(N + 1); for (int i = 1; i <= N; i++) { if (!isCycle[i]) children[a[i]].push_back(i); } vector<int> parent(N + 1, 0), treeRoot(N + 1, 0); vector<int> order; order.reserve(N); vector<int> st; for (int r : roots) { parent[r] = 0; treeRoot[r] = r; st.push_back(r); while (!st.empty()) { int v = st.back(); st.pop_back(); order.push_back(v); for (int u : children[v]) { parent[u] = v; treeRoot[u] = r; st.push_back(u); } } } vector<long long> subtreeSize(N + 1, 1); for (auto it = order.rbegin(); it != order.rend(); ++it) { int v = *it; if (parent[v]) subtreeSize[parent[v]] += subtreeSize[v]; } // Heavy-light decomposition of the rooted forest. vector<int> heavy(N + 1, 0); for (int v = 1; v <= N; v++) { for (int u : children[v]) { if (!heavy[v] || subtreeSize[u] > subtreeSize[heavy[v]]) { heavy[v] = u; } } } vector<int> head(N + 1, 0), pos(N + 1, 0), rev(N + 1, 0); int timer = 1; vector<pair<int, int>> decomposeStack; for (int r : roots) decomposeStack.push_back({r, r}); while (!decomposeStack.empty()) { auto [start, h] = decomposeStack.back(); decomposeStack.pop_back(); int v = start; while (v) { head[v] = h; pos[v] = timer; rev[timer] = v; timer++; for (int u : children[v]) { if (u != heavy[v]) decomposeStack.push_back({u, u}); } v = heavy[v]; } } // F(v): if v is unmarked, the sum of subtree sizes of the topmost // parties below v; if v is marked, F(v) = subtreeSize[v]. Fenwick treeDelta(N); vector<set<int>> chainMarks(N + 1); auto nearestMarkedAncestor = [&](int v) { while (v) { auto &marks = chainMarks[head[v]]; auto it = marks.upper_bound(pos[v]); if (it != marks.begin()) { --it; return rev[*it]; } v = parent[head[v]]; } return 0; }; // Add delta on the path from v upwards, stopping just below p. // p = 0 means update through the root. auto addVisiblePath = [&](int v, int p, long long delta) { if (p == 0) { while (v) { treeDelta.rangeAdd(pos[head[v]], pos[v], delta); v = parent[head[v]]; } return; } while (head[v] != head[p]) { treeDelta.rangeAdd(pos[head[v]], pos[v], delta); v = parent[head[v]]; } treeDelta.rangeAdd(pos[p] + 1, pos[v], delta); }; // Number of cows from each cycle tree that still reach the cycle. Fenwick cycleWeights(totalCycleVertices); for (const auto &comp : comps) { for (int i = 0; i < (int)comp.nodes.size(); i++) { cycleWeights.add(comp.offset + i + 1, subtreeSize[comp.nodes[i]]); } } auto cycleRangeSum = [&](const CycleComponent &comp, int l, int r) { if (l > r) return 0LL; return cycleWeights.sum(comp.offset + r + 1) - cycleWeights.sum(comp.offset + l); }; // For a marked vertex, sum of subtree sizes of its topmost marked // descendants in the virtual party tree. vector<long long> below(N + 1, 0); vector<int> color(N + 1, 0); // 0 = no party, 1 = C, 2 = O, 3 = W. long long answer[4] = {0, 0, 0, 0}; auto insertParty = [&](int v, int newColor) { long long previousTopmost = treeDelta.pointQuery(pos[v]); int p = nearestMarkedAncestor(v); long long delta = subtreeSize[v] - previousTopmost; addVisiblePath(v, p, delta); below[v] = previousTopmost; if (p) below[p] += delta; color[v] = newColor; chainMarks[head[v]].insert(pos[v]); if (p) { // The new party takes delta attendees from its nearest party ancestor. answer[color[p]] -= delta; answer[newColor] += delta; return; } if (!isCycle[v]) { // The residual weight of this cycle tree decreases. int r = treeRoot[v]; CycleComponent &comp = comps[compOf[r]]; int j = cyclePos[r]; if (!comp.parties.empty()) { auto it = comp.parties.lower_bound(j); if (it == comp.parties.end()) it = comp.parties.begin(); int nextParty = comp.nodes[*it]; answer[color[nextParty]] -= delta; } answer[newColor] += delta; cycleWeights.add(comp.offset + j + 1, -delta); return; } // Inserting a party directly on a cycle. CycleComponent &comp = comps[compOf[v]]; int i = cyclePos[v]; int len = (int)comp.nodes.size(); long long gained; if (comp.parties.empty()) { gained = cycleRangeSum(comp, 0, len - 1); } else { auto it = comp.parties.lower_bound(i); if (it == comp.parties.begin()) it = comp.parties.end(); --it; int previous = *it; auto jt = comp.parties.upper_bound(i); if (jt == comp.parties.end()) jt = comp.parties.begin(); int nextParty = comp.nodes[*jt]; // Residual weights in the cyclic arc (previous, i]. if (previous < i) { gained = cycleRangeSum(comp, previous + 1, i); } else { gained = cycleRangeSum(comp, previous + 1, len - 1) + cycleRangeSum(comp, 0, i); } answer[color[nextParty]] -= gained; } answer[newColor] += gained; // The old residual weight at this root was exactly delta. cycleWeights.add(comp.offset + i + 1, -delta); comp.parties.insert(i); }; auto cyclePartyBasin = [&](int v) { CycleComponent &comp = comps[compOf[v]]; int i = cyclePos[v]; int len = (int)comp.nodes.size(); auto it = comp.parties.lower_bound(i); if (it == comp.parties.begin()) it = comp.parties.end(); --it; int previous = *it; // Residual weights strictly between previous and i on the cycle. long long residual; if (previous < i) { residual = cycleRangeSum(comp, previous + 1, i - 1); } else { residual = cycleRangeSum(comp, previous + 1, len - 1) + cycleRangeSum(comp, 0, i - 1); } return subtreeSize[v] - below[v] + residual; }; while (M--) { int v; char type; cin >> v >> type; int newColor = (type == 'C' ? 1 : (type == 'O' ? 2 : 3)); if (color[v] == 0) { insertParty(v, newColor); } else if (color[v] != newColor) { long long basin; if (isCycle[v]) basin = cyclePartyBasin(v); else basin = subtreeSize[v] - below[v]; answer[color[v]] -= basin; answer[newColor] += basin; color[v] = newColor; } cout << answer[1] << ' ' << answer[2] << ' ' << answer[3] << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; struct Info { int sz = 0; int cnt[3] = {0, 0, 0}; }; static inline void addInfo(Info &a, const Info &b, int sign = 1) { a.sz += sign * b.sz; for (int t = 0; t < 3; ++t) a.cnt[t] += sign * b.cnt[t]; } struct LinkCutTree { int n; vector<array<int, 2>> ch; vector<int> fa, stk; vector<unsigned char> rev; vector<Info> base, vir, sum; explicit LinkCutTree(int n_) : n(n_), ch(n_ + 1), fa(n_ + 1, 0), stk(n_ + 1), rev(n_ + 1, 0), base(n_ + 1), vir(n_ + 1), sum(n_ + 1) { for (int i = 1; i <= n; ++i) { ch[i] = {0, 0}; base[i].sz = 1; pull(i); } } bool isRoot(int x) const { int p = fa[x]; return p == 0 || (ch[p][0] != x && ch[p][1] != x); } void pull(int x) { sum[x] = base[x]; addInfo(sum[x], vir[x]); if (ch[x][0]) addInfo(sum[x], sum[ch[x][0]]); if (ch[x][1]) addInfo(sum[x], sum[ch[x][1]]); } void push(int x) { if (!rev[x]) return; swap(ch[x][0], ch[x][1]); if (ch[x][0]) rev[ch[x][0]] ^= 1; if (ch[x][1]) rev[ch[x][1]] ^= 1; rev[x] = 0; } void rotate(int x) { int y = fa[x], z = fa[y]; int dx = (ch[y][1] == x); int dy = (ch[z][1] == y); if (!isRoot(y)) ch[z][dy] = x; fa[x] = z; int b = ch[x][dx ^ 1]; ch[y][dx] = b; if (b) fa[b] = y; ch[x][dx ^ 1] = y; fa[y] = x; pull(y); pull(x); } void splay(int x) { int top = 0, y = x; stk[top++] = y; while (!isRoot(y)) { y = fa[y]; stk[top++] = y; } while (top) push(stk[--top]); while (!isRoot(x)) { y = fa[x]; int z = fa[y]; if (!isRoot(y)) { bool zigzig = ((ch[y][0] == x) == (ch[z][0] == y)); rotate(zigzig ? y : x); } rotate(x); } } void access(int x) { int y = 0; for (int u = x; u; u = fa[u]) { splay(u); if (ch[u][1]) addInfo(vir[u], sum[ch[u][1]], 1); if (y) addInfo(vir[u], sum[y], -1); ch[u][1] = y; pull(u); y = u; } splay(x); } void makeRoot(int x) { access(x); rev[x] ^= 1; } int findRoot(int x) { access(x); while (true) { push(x); if (!ch[x][0]) break; x = ch[x][0]; } splay(x); return x; } bool link(int x, int y) { makeRoot(x); if (findRoot(y) == x) return false; access(y); fa[x] = y; addInfo(vir[y], sum[x], 1); pull(y); return true; } void cut(int x, int y) { makeRoot(x); access(y); // x and y are directly adjacent, with x the left child of y. ch[y][0] = 0; fa[x] = 0; pull(y); } Info componentInfo(int x) { return sum[findRoot(x)]; } void changeParty(int x, int oldType, int newType) { access(x); if (oldType >= 0) --base[x].cnt[oldType]; ++base[x].cnt[newType]; pull(x); } }; struct DSU { vector<int> p, sz; explicit DSU(int n) : p(n + 1), sz(n + 1, 1) { iota(p.begin(), p.end(), 0); } int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); } void unite(int a, int b) { a = find(a); b = find(b); if (a == b) return; if (sz[a] < sz[b]) swap(a, b); p[b] = a; sz[a] += sz[b]; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N + 1); for (int i = 1; i <= N; ++i) cin >> a[i]; DSU dsu(N); vector<int> indeg(N + 1, 0); for (int i = 1; i <= N; ++i) { dsu.unite(i, a[i]); ++indeg[a[i]]; } // Mark vertices lying on directed cycles by removing all tree vertices. queue<int> q; for (int i = 1; i <= N; ++i) { if (indeg[i] == 0) q.push(i); } while (!q.empty()) { int v = q.front(); q.pop(); if (--indeg[a[v]] == 0) q.push(a[v]); } vector<unsigned char> onCycle(N + 1, 0); for (int i = 1; i <= N; ++i) onCycle[i] = (indeg[i] > 0); vector<int> comp(N + 1); for (int i = 1; i <= N; ++i) comp[i] = dsu.find(i); LinkCutTree lct(N); // Each component initially has one extra edge closing its unique cycle. // All other edges are stored in the link-cut forest. vector<int> extra(N + 1, 0); for (int i = 1; i <= N; ++i) { if (i == a[i]) { extra[comp[i]] = i; } else if (!lct.link(i, a[i])) { extra[comp[i]] = i; } } int M; cin >> M; vector<int> partyType(N + 1, -1); long long answer[3] = {0, 0, 0}; auto typeOf = [](char c) { if (c == 'C') return 0; if (c == 'O') return 1; return 2; }; while (M--) { int v; char vc; cin >> v >> vc; int nt = typeOf(vc); if (partyType[v] != -1) { int ot = partyType[v]; int attendees = lct.componentInfo(v).sz; answer[ot] -= attendees; answer[nt] += attendees; lct.changeParty(v, ot, nt); partyType[v] = nt; } else { Info before = lct.componentInfo(v); int ot = -1; for (int t = 0; t < 3; ++t) { if (before.cnt[t] > 0) ot = t; } int id = comp[v]; int ex = extra[id]; if (ot == -1) { // The component still contains its original directed cycle. if (v == ex) { // Removing the already omitted edge breaks the cycle. extra[id] = 0; } else if (onCycle[v]) { // Replace the removed cycle edge by the omitted one, // preserving undirected connectivity. lct.cut(v, a[v]); lct.link(ex, a[ex]); extra[id] = 0; } else { // A tree edge is cut; the cycle remains in the other part. lct.cut(v, a[v]); } } else { // This component already has a party at its root. lct.cut(v, a[v]); } int attendees = lct.componentInfo(v).sz; if (ot != -1) answer[ot] -= attendees; answer[nt] += attendees; lct.changeParty(v, -1, nt); partyType[v] = nt; } cout << answer[0] << ' ' << answer[1] << ' ' << answer[2] << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; struct Fenwick { int n; vector<long long> bit; explicit Fenwick(int n_) : n(n_), bit(n_ + 1, 0) {} void add(int idx, long long val) { for (int i = idx + 1; i <= n; i += i & -i) bit[i] += val; } long long prefix(int idx) const { long long res = 0; for (int i = idx + 1; i > 0; i -= i & -i) res += bit[i]; return res; } long long rangeSum(int l, int r) const { if (l > r) return 0; return prefix(r) - (l ? prefix(l - 1) : 0); } }; struct MaxSeg { int n; vector<pair<int, int>> tree; // (depth, vertex) static pair<int, int> better(const pair<int, int>& a, const pair<int, int>& b) { return a.first > b.first ? a : b; } explicit MaxSeg(int n_) : n(n_), tree(2 * n_, {-1, 0}) {} void update(int pos, int depth, int vertex) { int p = pos + n; tree[p] = {depth, vertex}; for (p >>= 1; p; p >>= 1) tree[p] = better(tree[p << 1], tree[p << 1 | 1]); } pair<int, int> query(int l, int r) const { pair<int, int> res = {-1, 0}; for (l += n, r += n + 1; l < r; l >>= 1, r >>= 1) { if (l & 1) res = better(res, tree[l++]); if (r & 1) res = better(res, tree[--r]); } return res; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N + 1), indeg(N + 1, 0); for (int i = 1; i <= N; ++i) { cin >> a[i]; ++indeg[a[i]]; } // Find cycle vertices by removing all tree vertices. vector<char> isCycle(N + 1, true); queue<int> que; for (int i = 1; i <= N; ++i) { if (indeg[i] == 0) que.push(i); } while (!que.empty()) { int v = que.front(); que.pop(); isCycle[v] = false; if (--indeg[a[v]] == 0) que.push(a[v]); } // Reverse edges, excluding edges between cycle vertices, form rooted trees. vector<vector<int>> children(N + 1); for (int v = 1; v <= N; ++v) { if (!isCycle[v]) children[a[v]].push_back(v); } vector<int> comp(N + 1, -1), cyclePos(N + 1, -1), globalCycleIdx(N + 1, -1); vector<int> compStart, compEnd; vector<int> cycleNode; vector<set<int>> activeCycleParties; for (int i = 1; i <= N; ++i) { if (!isCycle[i] || comp[i] != -1) continue; int id = (int)compStart.size(); int start = (int)cycleNode.size(); int pos = 0; int v = i; do { comp[v] = id; cyclePos[v] = pos++; globalCycleIdx[v] = (int)cycleNode.size(); cycleNode.push_back(v); v = a[v]; } while (v != i); compStart.push_back(start); compEnd.push_back((int)cycleNode.size()); activeCycleParties.emplace_back(); } int K = (int)cycleNode.size(); vector<int> parent(N + 1, 0), depth(N + 1, 0), root(N + 1, 0); vector<int> sz(N + 1, 1), heavy(N + 1, 0); vector<int> order; order.reserve(N); for (int r : cycleNode) { root[r] = r; stack<int> st; st.push(r); while (!st.empty()) { int v = st.top(); st.pop(); order.push_back(v); for (int u : children[v]) { parent[u] = v; depth[u] = depth[v] + 1; root[u] = r; comp[u] = comp[r]; st.push(u); } } } for (auto it = order.rbegin(); it != order.rend(); ++it) { int v = *it; int p = parent[v]; if (p) { sz[p] += sz[v]; if (!heavy[p] || sz[v] > sz[heavy[p]]) heavy[p] = v; } } // Heavy-light decomposition. Its numbering also gives contiguous subtrees. vector<int> head(N + 1, 0), dfn(N + 1, 0); int timer = 0; for (int r : cycleNode) { stack<pair<int, int>> st; st.emplace(r, r); while (!st.empty()) { auto [v, h] = st.top(); st.pop(); int u = v; while (u) { head[u] = h; dfn[u] = timer++; for (int w : children[u]) { if (w != heavy[u]) st.emplace(w, w); } u = heavy[u]; } } } Fenwick cycleWeights(K); for (int r : cycleNode) { cycleWeights.add(globalCycleIdx[r], sz[r]); } // For non-cycle parties, a subtree query gives the sum of subtree sizes // of the highest existing parties in that subtree. Fenwick treeCoefficients(N); MaxSeg nearestPartySeg(N); auto nearestTreeParty = [&](int v) { int u = v; while (u) { auto res = nearestPartySeg.query(dfn[head[u]], dfn[u]); if (res.first != -1) return res.second; u = parent[head[u]]; } return 0; }; vector<int> state(N + 1, 0); // 0 = none, 1 = C, 2 = O, 3 = W vector<long long> area(N + 1, 0); long long answer[4] = {0, 0, 0, 0}; int M; cin >> M; while (M--) { int v; char type; cin >> v >> type; int color = (type == 'C' ? 1 : (type == 'O' ? 2 : 3)); if (state[v]) { int old = state[v]; if (old != color) { answer[old] -= area[v]; answer[color] += area[v]; state[v] = color; } } else if (!isCycle[v]) { int p = nearestTreeParty(v); long long covered = treeCoefficients.rangeSum( dfn[v], dfn[v] + sz[v] - 1); long long gained = (long long)sz[v] - covered; treeCoefficients.add(dfn[v], gained); if (p) { treeCoefficients.add(dfn[p], -gained); area[p] -= gained; answer[state[p]] -= gained; } else { int r = root[v]; cycleWeights.add(globalCycleIdx[r], -gained); int cid = comp[r]; auto& parties = activeCycleParties[cid]; if (!parties.empty()) { auto it = parties.lower_bound(cyclePos[r]); int qpos = (it == parties.end() ? *parties.begin() : *it); int q = cycleNode[compStart[cid] + qpos]; area[q] -= gained; answer[state[q]] -= gained; } } state[v] = color; area[v] = gained; answer[color] += gained; nearestPartySeg.update(dfn[v], depth[v], v); } else { int cid = comp[v]; int pos = cyclePos[v]; int start = compStart[cid]; int end = compEnd[cid]; int len = end - start; auto& parties = activeCycleParties[cid]; long long gained; if (parties.empty()) { gained = cycleWeights.rangeSum(start, end - 1); } else { auto it = parties.lower_bound(pos); int previousPos; if (it == parties.begin()) { previousPos = *prev(parties.end()); } else { --it; previousPos = *it; } auto nextIt = parties.lower_bound(pos); int nextPos = (nextIt == parties.end() ? *parties.begin() : *nextIt); int nextParty = cycleNode[start + nextPos]; if (previousPos < pos) { gained = cycleWeights.rangeSum( start + previousPos + 1, start + pos); } else { gained = 0; if (previousPos + 1 < len) { gained += cycleWeights.rangeSum( start + previousPos + 1, end - 1); } gained += cycleWeights.rangeSum(start, start + pos); } area[nextParty] -= gained; answer[state[nextParty]] -= gained; } state[v] = color; area[v] = gained; answer[color] += gained; parties.insert(pos); } cout << answer[1] << ' ' << answer[2] << ' ' << answer[3] << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static const int MAXN = 200005; struct LinkCut { int ch[MAXN][2], fa[MAXN], vir[MAXN], siz[MAXN]; void init(int n) { for (int i = 1; i <= n; i++) { ch[i][0] = ch[i][1] = 0; fa[i] = vir[i] = 0; siz[i] = 1; } siz[0] = vir[0] = 0; } bool isRoot(int x) { return fa[x] == 0 || (ch[fa[x]][0] != x && ch[fa[x]][1] != x); } void pushUp(int x) { siz[x] = 1 + vir[x] + siz[ch[x][0]] + siz[ch[x][1]]; } void rotate(int x) { int y = fa[x], z = fa[y]; int dx = (ch[y][1] == x); int b = ch[x][dx ^ 1]; if (!isRoot(y)) { if (ch[z][0] == y) ch[z][0] = x; else if (ch[z][1] == y) ch[z][1] = x; } fa[x] = z; ch[x][dx ^ 1] = y; fa[y] = x; ch[y][dx] = b; if (b) fa[b] = y; pushUp(y); pushUp(x); } void splay(int x) { while (!isRoot(x)) { int y = fa[x], z = fa[y]; if (!isRoot(y)) { if ((ch[y][0] == x) ^ (ch[z][0] == y)) rotate(x); else rotate(y); } rotate(x); } } void access(int x) { int last = 0; for (int u = x; u; u = fa[u]) { splay(u); int old = ch[u][1]; if (old) vir[u] += siz[old]; if (last) vir[u] -= siz[last]; ch[u][1] = last; if (last) fa[last] = u; pushUp(u); last = u; } splay(x); } int findRoot(int x) { access(x); while (ch[x][0]) x = ch[x][0]; splay(x); return x; } int subtreeSize(int x) { access(x); return 1 + vir[x]; } int componentSize(int root) { access(root); return 1 + vir[root]; } void link(int x, int y) { access(x); access(y); fa[x] = y; vir[y] += siz[x]; pushUp(y); } void cutParent(int x) { access(x); int l = ch[x][0]; ch[x][0] = 0; if (l) fa[l] = 0; pushUp(x); } }; int N, M; int a[MAXN]; bool isCycle[MAXN]; bool removedEdge[MAXN]; bool activeCow[MAXN]; int typ[MAXN]; int basinSize[MAXN]; LinkCut lct; int id(char c) { if (c == 'C') return 0; if (c == 'O') return 1; return 2; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> N; for (int i = 1; i <= N; i++) { cin >> a[i]; } vector<int> indeg(N + 1, 0); for (int i = 1; i <= N; i++) { indeg[a[i]]++; } queue<int> q; for (int i = 1; i <= N; i++) { if (indeg[i] == 0) q.push(i); } while (!q.empty()) { int u = q.front(); q.pop(); int v = a[u]; indeg[v]--; if (indeg[v] == 0) q.push(v); } for (int i = 1; i <= N; i++) { if (indeg[i] > 0) isCycle[i] = true; } vector<bool> visited(N + 1, false); for (int i = 1; i <= N; i++) { if (isCycle[i] && !visited[i]) { removedEdge[i] = true; int u = i; do { visited[u] = true; u = a[u]; } while (u != i); } } lct.init(N); for (int v = 1; v <= N; v++) { if (!removedEdge[v]) { lct.link(v, a[v]); } } cin >> M; long long ans[3] = {0, 0, 0}; while (M--) { int c; char ch; cin >> c >> ch; int t = id(ch); if (activeCow[c]) { if (typ[c] != t) { int s = basinSize[c]; ans[typ[c]] -= s; ans[t] += s; typ[c] = t; } } else { int root = lct.findRoot(c); if (activeCow[root]) { int s = lct.subtreeSize(c); int oldType = typ[root]; ans[oldType] -= s; basinSize[root] -= s; lct.cutParent(c); activeCow[c] = true; typ[c] = t; basinSize[c] = s; ans[t] += s; } else { if (isCycle[c]) { int s = lct.componentSize(root); if (c != root) { lct.cutParent(c); lct.link(root, a[root]); } activeCow[c] = true; typ[c] = t; basinSize[c] = s; ans[t] += s; } else { int s = lct.subtreeSize(c); lct.cutParent(c); activeCow[c] = true; typ[c] = t; basinSize[c] = s; ans[t] += s; } } } cout << ans[0] << ' ' << ans[1] << ' ' << ans[2] << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; struct Fenwick { int n; vector<long long> bit; Fenwick() : n(0) {} Fenwick(int n) { init(n); } void init(int n_) { n = n_; bit.assign(n + 1, 0); } void add(int idx, long long delta) { for (++idx; idx <= n; idx += idx & -idx) bit[idx] += delta; } long long sumPrefix(int idx) const { long long res = 0; for (; idx > 0; idx -= idx & -idx) res += bit[idx]; return res; } long long rangeSum(int l, int r) const { if (l > r) return 0; return sumPrefix(r + 1) - sumPrefix(l); } }; struct SegTree { int n; vector<pair<int, int>> seg; SegTree() : n(1) {} SegTree(int sz) { init(sz); } void init(int sz) { n = 1; while (n < max(1, sz)) n <<= 1; seg.assign(2 * n, {-1, -1}); } void update(int idx, int dep, int id) { int p = idx + n; seg[p] = {dep, id}; for (p >>= 1; p; p >>= 1) { seg[p] = max(seg[p << 1], seg[p << 1 | 1]); } } pair<int, int> query(int l, int r) const { if (l > r) return {-1, -1}; l += n; r += n; pair<int, int> res = {-1, -1}; while (l <= r) { if (l & 1) res = max(res, seg[l++]); if (!(r & 1)) res = max(res, seg[r--]); l >>= 1; r >>= 1; } return res; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N + 1); vector<int> indeg(N + 1, 0); vector<vector<int>> rev(N + 1); for (int i = 1; i <= N; i++) { cin >> a[i]; indeg[a[i]]++; rev[a[i]].push_back(i); } int M; cin >> M; vector<int> qc(M); vector<char> qt(M); for (int i = 0; i < M; i++) { cin >> qc[i] >> qt[i]; } // Find cycle nodes by removing indegree-zero nodes. vector<char> isCycle(N + 1, 1); vector<int> deg = indeg; queue<int> qu; for (int i = 1; i <= N; i++) { if (deg[i] == 0) qu.push(i); } while (!qu.empty()) { int u = qu.front(); qu.pop(); isCycle[u] = 0; int v = a[u]; if (--deg[v] == 0) qu.push(v); } // Decompose cycles. vector<int> comp(N + 1, -1), cpos(N + 1, -1); vector<vector<int>> compCycle; for (int i = 1; i <= N; i++) { if (isCycle[i] && comp[i] == -1) { int cid = (int)compCycle.size(); vector<int> vec; int cur = i; do { comp[cur] = cid; cpos[cur] = (int)vec.size(); vec.push_back(cur); cur = a[cur]; } while (cur != i); compCycle.push_back(vec); } } int numComps = (int)compCycle.size(); vector<int> compBase(numComps), compLen(numComps); vector<int> cycleGidx(N + 1, -1); int Ccnt = 0; for (int cid = 0; cid < numComps; cid++) { compBase[cid] = Ccnt; compLen[cid] = (int)compCycle[cid].size(); for (int p = 0; p < compLen[cid]; p++) { int cow = compCycle[cid][p]; cycleGidx[cow] = Ccnt + p; } Ccnt += compLen[cid]; } // Build non-cycle forest. vector<int> parentTree(N + 1, -1); vector<int> depth(N + 1, 0); vector<int> rootCycle(N + 1, -1); vector<int> heavy(N + 1, -1); vector<int> head(N + 1, -1); vector<int> pos(N + 1, -1); vector<int> order; vector<int> forestRoots; vector<int> st; for (int r = 1; r <= N; r++) { if (!isCycle[r]) continue; for (int v : rev[r]) { if (isCycle[v]) continue; parentTree[v] = -1; depth[v] = 0; rootCycle[v] = r; forestRoots.push_back(v); st.clear(); st.push_back(v); while (!st.empty()) { int u = st.back(); st.pop_back(); order.push_back(u); for (int w : rev[u]) { if (isCycle[w]) continue; parentTree[w] = u; depth[w] = depth[u] + 1; rootCycle[w] = r; st.push_back(w); } } } } vector<int> sz(N + 1, 1); for (int i = (int)order.size() - 1; i >= 0; i--) { int u = order[i]; int p = parentTree[u]; if (p != -1) { sz[p] += sz[u]; if (heavy[p] == -1 || sz[u] > sz[heavy[p]]) { heavy[p] = u; } } } // Heavy-light decomposition for non-cycle nodes. int timer = 0; vector<pair<int, int>> st2; for (int root : forestRoots) { st2.clear(); st2.push_back({root, root}); while (!st2.empty()) { auto [u, h] = st2.back(); st2.pop_back(); int cur = u; while (cur != -1) { head[cur] = h; pos[cur] = timer++; for (int w : rev[cur]) { if (isCycle[w]) continue; if (w != heavy[cur]) { st2.push_back({w, w}); } } cur = heavy[cur]; } } } int nonCycleCount = timer; // Initial cycle weights: cycle cow itself + all attached non-cycle nodes. vector<long long> Winit(Ccnt, 0); for (int i = 1; i <= N; i++) { if (isCycle[i]) { Winit[cycleGidx[i]] = 1; } } for (int i = 1; i <= N; i++) { if (!isCycle[i]) { int r = rootCycle[i]; Winit[cycleGidx[r]]++; } } Fenwick bitW(Ccnt); for (int i = 0; i < Ccnt; i++) { if (Winit[i]) bitW.add(i, Winit[i]); } vector<set<int>> activeSet(numComps); vector<char> active(N + 1, 0); vector<int> color(N + 1, -1); vector<long long> terr(N + 1, 0); long long ans[3] = {0, 0, 0}; Fenwick bitTerr(nonCycleCount); SegTree seg(nonCycleCount); auto rangeAfter = [&](int cid, int from, int to) -> long long { int base = compBase[cid]; int len = compLen[cid]; if (from < to) { return bitW.rangeSum(base + from + 1, base + to); } else if (from > to) { long long res = 0; if (from + 1 <= len - 1) { res += bitW.rangeSum(base + from + 1, base + len - 1); } res += bitW.rangeSum(base, base + to); return res; } else { return bitW.rangeSum(base, base + len - 1); } }; auto decreaseW = [&](int cycCow, long long delta) { int cid = comp[cycCow]; int p = cpos[cycCow]; auto &s = activeSet[cid]; if (!s.empty()) { auto it = s.lower_bound(p); if (it == s.end()) it = s.begin(); int qpos = *it; int qid = compCycle[cid][qpos]; terr[qid] -= delta; ans[color[qid]] -= delta; } int gid = cycleGidx[cycCow]; bitW.add(gid, -delta); }; auto queryPath = [&](int x) -> int { pair<int, int> best = {-1, -1}; while (x != -1) { int h = head[x]; auto cur = seg.query(pos[h], pos[x]); if (cur.first > best.first) best = cur; x = parentTree[h]; } return best.second; }; auto activateCycle = [&](int x, int v) { int cid = comp[x]; int p = cpos[x]; auto &s = activeSet[cid]; long long t; if (s.empty()) { int base = compBase[cid]; int len = compLen[cid]; t = bitW.rangeSum(base, base + len - 1); terr[x] = t; color[x] = v; active[x] = 1; s.insert(p); ans[v] += t; } else { auto itq = s.lower_bound(p); if (itq == s.end()) itq = s.begin(); int qpos = *itq; int qid = compCycle[cid][qpos]; auto itp = itq; if (itp == s.begin()) itp = prev(s.end()); else --itp; int ppos = *itp; t = rangeAfter(cid, ppos, p); terr[qid] -= t; ans[color[qid]] -= t; terr[x] = t; color[x] = v; active[x] = 1; s.insert(p); ans[v] += t; } }; auto activateNonCycle = [&](int x, int v) { long long covered = bitTerr.rangeSum(pos[x], pos[x] + sz[x] - 1); long long t = (long long)sz[x] - covered; int p = queryPath(x); if (p != -1) { terr[p] -= t; bitTerr.add(pos[p], -t); ans[color[p]] -= t; } else { int r = rootCycle[x]; decreaseW(r, t); } terr[x] = t; color[x] = v; active[x] = 1; bitTerr.add(pos[x], t); seg.update(pos[x], depth[x], x); ans[v] += t; }; for (int i = 0; i < M; i++) { int c = qc[i]; char ch = qt[i]; int v; if (ch == 'C') v = 0; else if (ch == 'O') v = 1; else v = 2; if (!active[c]) { if (isCycle[c]) { activateCycle(c, v); } else { activateNonCycle(c, v); } } else { if (color[c] != v) { ans[color[c]] -= terr[c]; ans[v] += terr[c]; color[c] = v; } } cout << ans[0] << ' ' << ans[1] << ' ' << ans[2] << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; struct Fenwick { int n; vector<long long> bit; Fenwick(int n = 0) { init(n); } void init(int n_) { n = n_; bit.assign(n + 1, 0); } void add(int idx, long long delta) { for (int i = idx + 1; i <= n; i += i & -i) { bit[i] += delta; } } long long sumPrefix(int idx) const { long long res = 0; for (int i = idx + 1; i > 0; i -= i & -i) { res += bit[i]; } return res; } long long range(int l, int r) const { if (l > r) return 0; return sumPrefix(r) - (l ? sumPrefix(l - 1) : 0); } }; struct MaxSeg { int n; vector<pair<int, int>> tr; MaxSeg(int n = 0) : n(n), tr(4 * max(1, n) + 5, {-1, -1}) {} void updateRec(int p, int l, int r, int ql, int qr, pair<int, int> val) { if (ql > r || qr < l) return; if (ql <= l && r <= qr) { if (val > tr[p]) tr[p] = val; return; } int m = (l + r) >> 1; updateRec(p << 1, l, m, ql, qr, val); updateRec(p << 1 | 1, m + 1, r, ql, qr, val); } void update(int l, int r, pair<int, int> val) { if (n == 0 || l > r) return; updateRec(1, 0, n - 1, l, r, val); } pair<int, int> queryRec(int p, int l, int r, int idx, pair<int, int> res) { if (tr[p] > res) res = tr[p]; if (l == r) return res; int m = (l + r) >> 1; if (idx <= m) return queryRec(p << 1, l, m, idx, res); else return queryRec(p << 1 | 1, m + 1, r, idx, res); } int query(int idx) { if (n == 0) return -1; return queryRec(1, 0, n - 1, idx, {-1, -1}).second; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N); for (int i = 0; i < N; i++) { cin >> a[i]; --a[i]; } int M; cin >> M; vector<int> uc(M), ut(M); for (int i = 0; i < M; i++) { int c; char t; cin >> c >> t; --c; uc[i] = c; if (t == 'C') ut[i] = 0; else if (t == 'O') ut[i] = 1; else ut[i] = 2; } // Find cycle vertices. vector<int> indeg(N, 0); for (int i = 0; i < N; i++) indeg[a[i]]++; queue<int> q; for (int i = 0; i < N; i++) { if (indeg[i] == 0) q.push(i); } vector<char> removed(N, 0); while (!q.empty()) { int u = q.front(); q.pop(); removed[u] = 1; int v = a[u]; if (--indeg[v] == 0) { q.push(v); } } vector<char> isCycle(N); for (int i = 0; i < N; i++) { isCycle[i] = !removed[i]; } vector<int> cycleId(N, -1), cyclePos(N, -1); vector<int> cycleLen, cycleOffset; int totalCycleNodes = 0; for (int i = 0; i < N; i++) { if (isCycle[i] && cycleId[i] == -1) { int cid = (int)cycleLen.size(); vector<int> order; int cur = i; do { order.push_back(cur); cur = a[cur]; } while (cur != i); cycleLen.push_back((int)order.size()); cycleOffset.push_back(totalCycleNodes); for (int pos = 0; pos < (int)order.size(); pos++) { int node = order[pos]; cycleId[node] = cid; cyclePos[node] = pos; } totalCycleNodes += (int)order.size(); } } // Build reverse forest, excluding cycle edges. vector<vector<int>> children(N); for (int i = 0; i < N; i++) { if (!isCycle[i]) { children[a[i]].push_back(i); } } vector<int> tin(N), tout(N), sz(N, 1), depth(N), parent(N, -1), rootCycle(N); int timer = 0; vector<pair<int, int>> st; st.reserve(N); for (int r = 0; r < N; r++) { if (!isCycle[r]) continue; parent[r] = -1; depth[r] = 0; rootCycle[r] = r; tin[r] = timer++; sz[r] = 1; st.clear(); st.push_back({r, 0}); while (!st.empty()) { int v = st.back().first; int &idx = st.back().second; if (idx < (int)children[v].size()) { int u = children[v][idx++]; parent[u] = v; depth[u] = depth[v] + 1; rootCycle[u] = rootCycle[v]; tin[u] = timer++; sz[u] = 1; st.push_back({u, 0}); } else { tout[v] = timer - 1; st.pop_back(); if (parent[v] != -1) { sz[parent[v]] += sz[v]; } } } } Fenwick bitDom(N); Fenwick bitCycle(totalCycleNodes); vector<long long> sumR(cycleLen.size(), 0); for (int i = 0; i < N; i++) { if (isCycle[i]) { int cid = cycleId[i]; int pos = cyclePos[i]; int gidx = cycleOffset[cid] + pos; long long val = sz[i]; bitCycle.add(gidx, val); sumR[cid] += val; } } vector<char> active(N, 0); vector<int> party(N, -1); vector<long long> dom(N, 0); vector<set<int>> activeCycle(cycleLen.size()); MaxSeg seg(N); long long ans[3] = {0, 0, 0}; for (int night = 0; night < M; night++) { int c = uc[night]; int col = ut[night]; if (active[c]) { if (party[c] != col) { long long s = dom[c]; ans[party[c]] -= s; ans[col] += s; party[c] = col; } } else { active[c] = 1; party[c] = col; if (isCycle[c]) { int cid = cycleId[c]; int pos = cyclePos[c]; int len = cycleLen[cid]; auto &S = activeCycle[cid]; long long s; int p = -1; if (S.empty()) { s = sumR[cid]; } else { auto it = S.lower_bound(pos); int pred; if (it == S.end()) { p = *S.begin(); pred = *S.rbegin(); } else { p = *it; if (it == S.begin()) { pred = *S.rbegin(); } else { auto itp = prev(it); pred = *itp; } } int off = cycleOffset[cid]; if (pred < pos) { s = bitCycle.range(off + pred + 1, off + pos); } else if (pred > pos) { s = 0; if (pred + 1 <= len - 1) { s += bitCycle.range(off + pred + 1, off + len - 1); } s += bitCycle.range(off, off + pos); } else { s = sumR[cid]; } } if (p != -1) { ans[party[p]] -= s; dom[p] -= s; } dom[c] = s; ans[col] += s; S.insert(pos); seg.update(tin[c], tout[c], {depth[c], c}); } else { long long sub = bitDom.range(tin[c], tout[c]); long long s = (long long)sz[c] - sub; int p = seg.query(tin[c]); bool pNonCycle = (p != -1 && !isCycle[p]); if (!pNonCycle) { int q = rootCycle[c]; int cid = cycleId[q]; sumR[cid] -= s; int gidx = cycleOffset[cid] + cyclePos[q]; bitCycle.add(gidx, -s); } if (p != -1) { ans[party[p]] -= s; dom[p] -= s; if (!isCycle[p]) { bitDom.add(tin[p], -s); } } dom[c] = s; ans[col] += s; bitDom.add(tin[c], s); seg.update(tin[c], tout[c], {depth[c], c}); } } cout << ans[0] << ' ' << ans[1] << ' ' << ans[2] << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; /* * Supports: * - range add * - range minimum together with the number of positions attaining it */ class MinCountSegmentTree { int n; vector<int> mn, cnt, lazy; static pair<int, int> combine(pair<int, int> a, pair<int, int> b) { if (a.first < b.first) return a; if (b.first < a.first) return b; return {a.first, a.second + b.second}; } void build(int p, int l, int r) { cnt[p] = r - l + 1; if (l == r) return; int mid = (l + r) / 2; build(p * 2, l, mid); build(p * 2 + 1, mid + 1, r); } void apply(int p, int value) { mn[p] += value; lazy[p] += value; } void push(int p) { if (lazy[p] == 0) return; apply(p * 2, lazy[p]); apply(p * 2 + 1, lazy[p]); lazy[p] = 0; } void pull(int p) { mn[p] = min(mn[p * 2], mn[p * 2 + 1]); cnt[p] = 0; if (mn[p * 2] == mn[p]) cnt[p] += cnt[p * 2]; if (mn[p * 2 + 1] == mn[p]) cnt[p] += cnt[p * 2 + 1]; } void add(int p, int l, int r, int ql, int qr, int value) { if (ql <= l && r <= qr) { apply(p, value); return; } push(p); int mid = (l + r) / 2; if (ql <= mid) add(p * 2, l, mid, ql, qr, value); if (qr > mid) add(p * 2 + 1, mid + 1, r, ql, qr, value); pull(p); } pair<int, int> query(int p, int l, int r, int ql, int qr) { if (ql <= l && r <= qr) return {mn[p], cnt[p]}; push(p); int mid = (l + r) / 2; if (qr <= mid) return query(p * 2, l, mid, ql, qr); if (ql > mid) return query(p * 2 + 1, mid + 1, r, ql, qr); return combine( query(p * 2, l, mid, ql, qr), query(p * 2 + 1, mid + 1, r, ql, qr) ); } public: explicit MinCountSegmentTree(int n) : n(n), mn(4 * n, 0), cnt(4 * n, 0), lazy(4 * n, 0) { build(1, 0, n - 1); } void add(int l, int r, int value) { add(1, 0, n - 1, l, r, value); } pair<int, int> query(int l, int r) { return query(1, 0, n - 1, l, r); } }; /* * Range "chmax" updates and point maximum queries. * Each update inserts an active vertex over its subtree interval. * The deepest active vertex containing a point is its nearest active ancestor. */ class RangeMaxPointQuery { int base; const vector<int>& depth; vector<int> tag; void relax(int& best, int candidate) const { if (candidate < 0) return; if (best < 0 || depth[candidate] > depth[best]) { best = candidate; } } public: explicit RangeMaxPointQuery(const vector<int>& depth) : depth(depth) { base = 1; while (base < (int)depth.size()) base <<= 1; tag.assign(2 * base, -1); } void update(int l, int r, int vertex) { l += base; r += base + 1; while (l < r) { if (l & 1) { relax(tag[l], vertex); ++l; } if (r & 1) { --r; relax(tag[r], vertex); } l >>= 1; r >>= 1; } } int query(int position) const { int best = -1; for (int p = position + base; p > 0; p >>= 1) { relax(best, tag[p]); } return best; } }; class Fenwick { int n; vector<int> bit; public: explicit Fenwick(const vector<int>& values) : n((int)values.size()), bit(n + 1, 0) { for (int i = 0; i < n; ++i) bit[i + 1] = values[i]; for (int i = 1; i <= n; ++i) { int j = i + (i & -i); if (j <= n) bit[j] += bit[i]; } } void add(int index, int delta) { for (int i = index + 1; i <= n; i += i & -i) { bit[i] += delta; } } // Sum of [0, r) int prefix(int r) const { int result = 0; for (int i = r; i > 0; i -= i & -i) result += bit[i]; return result; } // Sum of [l, r) int rangeSum(int l, int r) const { return prefix(r) - prefix(l); } }; struct CycleInfo { int start; int len; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N); vector<int> indegree(N, 0); for (int i = 0; i < N; ++i) { cin >> a[i]; --a[i]; ++indegree[a[i]]; } // Remove all non-cycle vertices. vector<int> queue; queue.reserve(N); for (int i = 0; i < N; ++i) { if (indegree[i] == 0) queue.push_back(i); } for (size_t head = 0; head < queue.size(); ++head) { int v = queue[head]; if (--indegree[a[v]] == 0) queue.push_back(a[v]); } vector<char> onCycle(N, false); for (int i = 0; i < N; ++i) onCycle[i] = (indegree[i] > 0); // Enumerate cycles in the direction in which cows move. vector<CycleInfo> cycles; vector<int> cycleVertices; vector<int> cycleId(N, -1), cycleLocal(N, -1); vector<char> seen(N, false); cycleVertices.reserve(N); for (int i = 0; i < N; ++i) { if (!onCycle[i] || seen[i]) continue; int id = (int)cycles.size(); int start = (int)cycleVertices.size(); int v = i; do { seen[v] = true; cycleId[v] = id; cycleLocal[v] = (int)cycleVertices.size() - start; cycleVertices.push_back(v); v = a[v]; } while (v != i); cycles.push_back({start, (int)cycleVertices.size() - start}); } /* * Cut cycle edges. The remaining edges form trees rooted at cycle vertices. * Children are stored in CSR format. */ vector<int> childStart(N + 1, 0); for (int v = 0; v < N; ++v) { if (!onCycle[v]) ++childStart[a[v] + 1]; } for (int i = 1; i <= N; ++i) childStart[i] += childStart[i - 1]; vector<int> childList(N - (int)cycleVertices.size()); vector<int> cursor = childStart; for (int v = 0; v < N; ++v) { if (!onCycle[v]) childList[cursor[a[v]]++] = v; } // Euler intervals, depths, tree roots, and subtree sizes. vector<int> tin(N), tout(N), depth(N), treeRoot(N), subtreeSize(N, 1); vector<int> dfsStack; dfsStack.reserve(2 * N); int timer = 0; for (int root : cycleVertices) { treeRoot[root] = root; depth[root] = 0; dfsStack.push_back(root); while (!dfsStack.empty()) { int code = dfsStack.back(); dfsStack.pop_back(); if (code >= 0) { int v = code; tin[v] = timer++; dfsStack.push_back(~v); for (int j = childStart[v + 1] - 1; j >= childStart[v]; --j) { int u = childList[j]; depth[u] = depth[v] + 1; treeRoot[u] = root; dfsStack.push_back(u); } } else { int v = ~code; tout[v] = timer - 1; if (!onCycle[v]) subtreeSize[a[v]] += subtreeSize[v]; } } } /* * residual[r]: cows from r's attached tree that reach the cycle without * encountering a party in that tree. */ vector<int> residual(N, 0); for (int root : cycleVertices) residual[root] = subtreeSize[root]; vector<int> fenwickValues(cycleVertices.size()); for (int i = 0; i < (int)cycleVertices.size(); ++i) { fenwickValues[i] = residual[cycleVertices[i]]; } Fenwick fenwick(fenwickValues); MinCountSegmentTree coverage(N); RangeMaxPointQuery nearestActiveAncestor(depth); // treeAssigned[v]: cows assigned to v's party inside its attached tree. vector<int> treeAssigned(N, 0); // cycleAssigned[i]: free cows assigned to the active marker at cycle index i. vector<int> cycleAssigned(cycleVertices.size(), 0); // -1 means no party; otherwise 0=C, 1=O, 2=W. vector<int> partyColor(N, -1); array<int, 3> answer{0, 0, 0}; // Active cycle markers, ordered by (cycle id, position in cycle). set<pair<int, int>> markers; vector<int> markerCount(cycles.size(), 0); auto cycleRangeSum = [&](int id, int l, int r) -> int { if (l > r) return 0; const auto& cycle = cycles[id]; return fenwick.rangeSum(cycle.start + l, cycle.start + r + 1); }; // Sum of residual cows in the cyclic interval (P, pos]. auto gapSum = [&](int id, int P, int pos) -> int { if (P == pos) return 0; if (P < pos) return cycleRangeSum(id, P + 1, pos); int result = cycleRangeSum(id, P + 1, cycles[id].len - 1); result += cycleRangeSum(id, 0, pos); return result; }; // First active marker at or after pos, cyclically. auto nextMarker = [&](int id, int pos) -> int { if (markerCount[id] == 0) return -1; auto it = markers.lower_bound({id, pos}); if (it != markers.end() && it->first == id) return it->second; it = markers.lower_bound({id, 0}); return it->second; }; // Previous and next old markers around an inactive position. auto markerNeighbors = [&](int id, int pos) -> pair<int, int> { auto first = markers.lower_bound({id, 0}); auto afterLast = markers.upper_bound({id, INT_MAX}); auto last = prev(afterLast); auto next = markers.upper_bound({id, pos}); if (next == markers.end() || next->first != id) next = first; int D = next->second; int P; if (next != first) { P = prev(next)->second; } else if (first != last) { P = prev(last)->second; } else { P = D; } return {P, D}; }; auto insertMarker = [&](int id, int pos, int color) { const auto& cycle = cycles[id]; int globalIndex = cycle.start + pos; if (markerCount[id] == 0) { // Every remaining free cow now reaches this marker. int amount = cycleRangeSum(id, 0, cycle.len - 1); cycleAssigned[globalIndex] = amount; answer[color] += amount; } else { auto [P, D] = markerNeighbors(id, pos); int amount = gapSum(id, P, pos); int globalD = cycle.start + D; cycleAssigned[globalD] -= amount; answer[partyColor[cycleVertices[globalD]]] -= amount; cycleAssigned[globalIndex] = amount; answer[color] += amount; } markers.insert({id, pos}); ++markerCount[id]; }; auto activate = [&](int v, int color) { int root = treeRoot[v]; int id = cycleId[root]; int rootPosition = cycleLocal[root]; int amount; int ancestor = -1; if (onCycle[v]) { // An inactive cycle root captures its entire remaining local basin. amount = residual[v]; } else { // Cows in v's subtree not already captured by active descendants. amount = coverage.query(tin[v], tout[v]).second; ancestor = nearestActiveAncestor.query(tin[v]); } if (ancestor != -1) { // These cows used to attend the nearest active ancestor. treeAssigned[ancestor] -= amount; answer[partyColor[ancestor]] -= amount; } else { // These cows previously reached the cycle. if (onCycle[v]) residual[v] = 0; else residual[root] -= amount; fenwick.add(cycles[id].start + rootPosition, -amount); int destination = nextMarker(id, rootPosition); if (destination != -1) { int globalDestination = cycles[id].start + destination; cycleAssigned[globalDestination] -= amount; answer[partyColor[cycleVertices[globalDestination]]] -= amount; } } treeAssigned[v] = amount; answer[color] += amount; partyColor[v] = color; if (onCycle[v]) { insertMarker(id, cycleLocal[v], color); } coverage.add(tin[v], tout[v], 1); nearestActiveAncestor.update(tin[v], tout[v], v); }; int M; cin >> M; while (M--) { int c; char type; cin >> c >> type; --c; int color = (type == 'C' ? 0 : (type == 'O' ? 1 : 2)); if (partyColor[c] == -1) { // Parties never disappear, so this is the cow's first activation. activate(c, color); } else if (partyColor[c] != color) { int oldColor = partyColor[c]; int localAmount = treeAssigned[c]; answer[oldColor] -= localAmount; answer[color] += localAmount; if (onCycle[c]) { int globalIndex = cycles[cycleId[c]].start + cycleLocal[c]; int cycleAmount = cycleAssigned[globalIndex]; answer[oldColor] -= cycleAmount; answer[color] += cycleAmount; } partyColor[c] = color; } cout << answer[0] << ' ' << answer[1] << ' ' << answer[2] << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; struct Fenwick { int n; vector<ll> bit; explicit Fenwick(int n = 0) : n(n), bit(n + 1, 0) {} void build(const vector<ll>& values) { n = (int)values.size(); bit.assign(n + 1, 0); for (int i = 1; i <= n; ++i) { bit[i] += values[i - 1]; int parent = i + (i & -i); if (parent <= n) bit[parent] += bit[i]; } } void add(int pos, ll delta) { for (int i = pos + 1; i <= n; i += i & -i) { bit[i] += delta; } } // Sum of [0, end). ll prefixSum(int end) const { ll result = 0; for (int i = end; i > 0; i -= i & -i) { result += bit[i]; } return result; } // Sum of [left, right], inclusive. ll rangeSum(int left, int right) const { if (left > right) return 0; return prefixSum(right + 1) - prefixSum(left); } }; // Supports inserting an active vertex's subtree and finding the deepest // active ancestor of a given Euler-tour position. struct AncestorMax { int base; const vector<int>& depth; vector<int> best; AncestorMax(int n, const vector<int>& depth) : depth(depth) { base = 1; while (base < n) base <<= 1; best.assign(base << 1, -1); } bool better(int a, int b) const { if (a == -1) return false; if (b == -1) return true; if (depth[a] != depth[b]) return depth[a] > depth[b]; return a > b; } void relax(int index, int candidate) { if (better(candidate, best[index])) { best[index] = candidate; } } void update(int left, int right, int candidate) { left += base; right += base; while (left <= right) { if (left & 1) relax(left++, candidate); if (!(right & 1)) relax(right--, candidate); left >>= 1; right >>= 1; } } int query(int pos) const { int answer = -1; for (int index = base + pos; index > 0; index >>= 1) { if (better(best[index], answer)) { answer = best[index]; } } return answer; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N); vector<int> indegree(N, 0); for (int i = 0; i < N; ++i) { cin >> a[i]; --a[i]; ++indegree[a[i]]; } // Remove all non-cycle vertices. At the same time, compute the size // of each rooted tree attached to a cycle vertex. vector<int> subtreeSize(N, 1); vector<int> queue; queue.reserve(N); for (int i = 0; i < N; ++i) { if (indegree[i] == 0) queue.push_back(i); } for (int qi = 0; qi < (int)queue.size(); ++qi) { int u = queue[qi]; int v = a[u]; subtreeSize[v] += subtreeSize[u]; if (--indegree[v] == 0) queue.push_back(v); } vector<char> onCycle(N, false); for (int i = 0; i < N; ++i) { onCycle[i] = (indegree[i] > 0); } // Store the cycles in directed order, using flat arrays. vector<int> cycleId(N, -1); vector<int> cyclePosition(N, -1); vector<int> cycleNodes; vector<int> cycleLength; vector<int> cycleBase; cycleNodes.reserve(N); for (int start = 0; start < N; ++start) { if (!onCycle[start] || cycleId[start] != -1) continue; int id = (int)cycleLength.size(); int base = (int)cycleNodes.size(); int u = start; do { cycleId[u] = id; cyclePosition[u] = (int)cycleNodes.size() - base; cycleNodes.push_back(u); u = a[u]; } while (u != start); cycleBase.push_back(base); cycleLength.push_back((int)cycleNodes.size() - base); } // Reverse adjacency, stored without per-vertex allocations. vector<int> head(N, -1); vector<int> nextChild(N, -1); for (int v = 0; v < N; ++v) { nextChild[v] = head[a[v]]; head[a[v]] = v; } // Euler tour of the forest obtained by removing all cycle edges. vector<int> tin(N); vector<int> rootOf(N, -1); vector<int> depth(N, 0); vector<int> stack; stack.reserve(N); for (int root : cycleNodes) { rootOf[root] = root; depth[root] = 0; stack.push_back(root); } int timer = 0; while (!stack.empty()) { int u = stack.back(); stack.pop_back(); tin[u] = timer++; for (int v = head[u]; v != -1; v = nextChild[v]) { if (onCycle[v]) continue; rootOf[v] = rootOf[u]; depth[v] = depth[u] + 1; stack.push_back(v); } } // Stores the current owner-count of each active non-cycle host. Fenwick hostTree(N); // For an inactive cycle vertex, weight is the number of cows from its // attached tree that reach the cycle. Active cycle vertices have weight 0. vector<ll> weight(cycleNodes.size(), 0); for (int id = 0; id < (int)cycleLength.size(); ++id) { int base = cycleBase[id]; for (int pos = 0; pos < cycleLength[id]; ++pos) { int u = cycleNodes[base + pos]; weight[base + pos] = subtreeSize[u]; } } Fenwick weightTree; weightTree.build(weight); vector<set<int>> activeCycleVertices(cycleLength.size()); auto changeWeight = [&](int id, int pos, ll delta) { int index = cycleBase[id] + pos; weight[index] += delta; weightTree.add(index, delta); }; // Sum of weights strictly after 'from' through 'to', following cycle order. auto cycleArcSum = [&](int id, int from, int to) -> ll { if (from == to) return 0; int base = cycleBase[id]; int last = base + cycleLength[id] - 1; if (from < to) { return weightTree.rangeSum(base + from + 1, base + to); } return weightTree.rangeSum(base + from + 1, last) + weightTree.rangeSum(base, base + to); }; AncestorMax ancestors(N, depth); vector<int> partyType(N, 0); // 0 = inactive, 1 = C, 2 = O, 3 = W vector<ll> hostCount(N, 0); array<ll, 4> answer{}; int M; cin >> M; for (int night = 0; night < M; ++night) { int c; char typeCharacter; cin >> c >> typeCharacter; --c; int newType; if (typeCharacter == 'C') newType = 1; else if (typeCharacter == 'O') newType = 2; else newType = 3; if (partyType[c] != 0) { // A host never stops hosting when its party type changes. if (partyType[c] != newType) { answer[partyType[c]] -= hostCount[c]; answer[newType] += hostCount[c]; partyType[c] = newType; } } else if (onCycle[c]) { int id = cycleId[c]; int pos = cyclePosition[c]; int base = cycleBase[id]; auto& active = activeCycleVertices[id]; ll countForNewHost; if (active.empty()) { // The first cycle host receives every cow that reaches the cycle. countForNewHost = weightTree.rangeSum( base, base + cycleLength[id] - 1 ); } else { auto it = active.lower_bound(pos); int successorPos; int predecessorPos; if (it == active.end()) { successorPos = *active.begin(); predecessorPos = *active.rbegin(); } else { successorPos = *it; if (it == active.begin()) { predecessorPos = *active.rbegin(); } else { predecessorPos = *prev(it); } } ll transferred = cycleArcSum(id, predecessorPos, pos); int successor = cycleNodes[base + successorPos]; answer[partyType[successor]] -= transferred; hostCount[successor] -= transferred; countForNewHost = transferred; } partyType[c] = newType; hostCount[c] = countForNewHost; answer[newType] += countForNewHost; int index = base + pos; ll oldWeight = weight[index]; changeWeight(id, pos, -oldWeight); active.insert(pos); ancestors.update(tin[c], tin[c] + subtreeSize[c] - 1, c); } else { // Cows already owned by active strict descendants do not change. ll shielded = hostTree.rangeSum( tin[c] + 1, tin[c] + subtreeSize[c] - 1 ); ll newlyHosted = (ll)subtreeSize[c] - shielded; int predecessor = ancestors.query(tin[c]); partyType[c] = newType; if (predecessor != -1) { // The nearest active tree ancestor currently owns these cows. answer[partyType[predecessor]] -= newlyHosted; hostCount[predecessor] -= newlyHosted; if (!onCycle[predecessor]) { hostTree.add(tin[predecessor], -newlyHosted); } } else { // These cows previously reached the cycle. int root = rootOf[c]; int id = cycleId[root]; int rootPos = cyclePosition[root]; auto& active = activeCycleVertices[id]; int successor = -1; if (!active.empty()) { auto it = active.lower_bound(rootPos); if (it == active.end()) it = active.begin(); successor = cycleNodes[cycleBase[id] + *it]; } if (successor != -1) { answer[partyType[successor]] -= newlyHosted; hostCount[successor] -= newlyHosted; } changeWeight(id, rootPos, -newlyHosted); } hostCount[c] = newlyHosted; answer[newType] += newlyHosted; hostTree.add(tin[c], newlyHosted); ancestors.update(tin[c], tin[c] + subtreeSize[c] - 1, c); } cout << answer[1] << ' ' << answer[2] << ' ' << answer[3] << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; struct Fenwick { int n; vector<ll> bit; explicit Fenwick(int n = 0) : n(n), bit(n + 1, 0) {} void build(const vector<ll>& values) { n = (int)values.size(); bit.assign(n + 1, 0); for (int i = 1; i <= n; ++i) bit[i] = values[i - 1]; for (int i = 1; i <= n; ++i) { int j = i + (i & -i); if (j <= n) bit[j] += bit[i]; } } // Indices are 0-based. void add(int index, ll value) { for (int i = index + 1; i <= n; i += i & -i) { bit[i] += value; } } ll prefixSum(int index) const { ll result = 0; for (int i = index + 1; i > 0; i -= i & -i) { result += bit[i]; } return result; } ll rangeSum(int left, int right) const { if (left > right || right < 0 || left >= n) return 0; left = max(left, 0); right = min(right, n - 1); return prefixSum(right) - prefixSum(left - 1); } }; // Supports range chmax updates and point maximum queries. // No pushes are necessary because updates only take maxima. struct RangeMaxPointQuery { int size; vector<ll> tag; explicit RangeMaxPointQuery(int n) { size = 1; while (size < n) size <<= 1; tag.assign(size << 1, 0); } // Left and right are 1-based and inclusive. void update(int left, int right, ll value) { left += size - 1; right += size - 1; while (left <= right) { if (left & 1) { tag[left] = max(tag[left], value); ++left; } if (!(right & 1)) { tag[right] = max(tag[right], value); --right; } left >>= 1; right >>= 1; } } // Position is 1-based. ll query(int position) const { ll result = 0; for (int p = position + size - 1; p > 0; p >>= 1) { result = max(result, tag[p]); } return result; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N + 1); vector<int> indegree(N + 1, 0); vector<int> head(N + 1, -1), nextChild(N + 1, -1); for (int i = 1; i <= N; ++i) { cin >> a[i]; ++indegree[a[i]]; nextChild[i] = head[a[i]]; head[a[i]] = i; } int M; cin >> M; // Remove all non-cycle vertices. vector<int> queue; queue.reserve(N); for (int i = 1; i <= N; ++i) { if (indegree[i] == 0) queue.push_back(i); } for (int qi = 0; qi < (int)queue.size(); ++qi) { int v = queue[qi]; if (--indegree[a[v]] == 0) { queue.push_back(a[v]); } } vector<char> onCycle(N + 1, false); for (int i = 1; i <= N; ++i) { onCycle[i] = (indegree[i] > 0); } // Store all cycles consecutively, in the direction of the edges. vector<int> component(N + 1, -1); vector<int> cycleIndex(N + 1, -1); vector<int> cycleNodes; vector<int> base, cycleLength; cycleNodes.reserve(N); for (int start = 1; start <= N; ++start) { if (!onCycle[start] || component[start] != -1) continue; int cid = (int)base.size(); int b = (int)cycleNodes.size(); base.push_back(b); int v = start; do { component[v] = cid; cycleIndex[v] = (int)cycleNodes.size(); cycleNodes.push_back(v); v = a[v]; } while (v != start); cycleLength.push_back((int)cycleNodes.size() - b); } // Removing cycle edges leaves a forest rooted at individual cycle vertices. vector<int> tin(N + 1), tout(N + 1), depth(N + 1); vector<int> rootCycle(N + 1); vector<int> stack; stack.reserve(2 * N); int timer = 0; for (int cid = 0; cid < (int)base.size(); ++cid) { for (int pos = 0; pos < cycleLength[cid]; ++pos) { int root = cycleNodes[base[cid] + pos]; rootCycle[root] = root; depth[root] = 0; stack.push_back(root); while (!stack.empty()) { int token = stack.back(); stack.pop_back(); if (token < 0) { tout[-token] = timer; continue; } int v = token; tin[v] = ++timer; stack.push_back(-v); for (int child = head[v]; child != -1; child = nextChild[child]) { if (onCycle[child]) continue; depth[child] = depth[v] + 1; rootCycle[child] = root; component[child] = cid; stack.push_back(child); } } } } vector<int> subtreeSize(N + 1); for (int v = 1; v <= N; ++v) { subtreeSize[v] = tout[v] - tin[v] + 1; } const int cycleCount = (int)cycleNodes.size(); // The weight of cycle position i is free(root of position i). vector<ll> initialWeights(cycleCount); for (int i = 0; i < cycleCount; ++i) { int root = cycleNodes[i]; initialWeights[i] = subtreeSize[root]; } Fenwick cycleWeights(cycleCount); cycleWeights.build(initialWeights); // free(v) = subtreeSize[v] + sum(delta[x] for x in subtree(v)). Fenwick delta(N); // Finds the deepest active ancestor of a vertex. RangeMaxPointQuery ancestorQuery(N); const ll KEY_BASE = N + 1LL; auto keyOf = [&](int v) -> ll { return depth[v] * KEY_BASE + v; }; // Global cycle indices; each component occupies one contiguous interval. set<int> activeCycle; auto firstActive = [&](int cid) -> int { int b = base[cid]; int e = b + cycleLength[cid]; auto it = activeCycle.lower_bound(b); if (it != activeCycle.end() && *it < e) return *it; return -1; }; auto lastActive = [&](int cid) -> int { int b = base[cid]; int e = b + cycleLength[cid]; auto it = activeCycle.lower_bound(e); if (it == activeCycle.begin()) return -1; --it; return (*it >= b ? *it : -1); }; auto nextActiveForEntry = [&](int cid, int position) -> int { int e = base[cid] + cycleLength[cid]; auto it = activeCycle.lower_bound(position); if (it != activeCycle.end() && *it < e) return *it; return firstActive(cid); }; // Sum of weights in the forward cycle arc (p, v]. auto arcSum = [&](int cid, int p, int v) -> ll { int b = base[cid]; int e = b + cycleLength[cid]; if (p < v) { return cycleWeights.rangeSum(p + 1, v); } return cycleWeights.rangeSum(p + 1, e - 1) + cycleWeights.rangeSum(b, v); }; vector<char> active(N + 1, false); vector<int> color(N + 1, -1); // Number of cows currently stopping at each active tree host. vector<ll> ownedTree(N + 1, 0); // Number of cows currently stopping at each active cycle host. vector<ll> ownerWeight(N + 1, 0); array<ll, 3> answer{0, 0, 0}; auto activateTree = [&](int u) { ll best = ancestorQuery.query(tin[u]); int p = (best == 0 ? 0 : (int)(best % KEY_BASE)); ll K = (ll)subtreeSize[u] + delta.rangeSum(tin[u], tout[u]); int root = rootCycle[u]; int cid = component[root]; int rootPosition = cycleIndex[root]; bool parentIsTree = (p != 0 && !onCycle[p]); if (parentIsTree) { ownedTree[p] -= K; answer[color[p]] -= K; } else if (p != 0) { // The closest active ancestor is this cycle vertex. ownerWeight[p] -= K; answer[color[p]] -= K; } else { // These cows previously continued around the cycle. int q = nextActiveForEntry(cid, rootPosition); if (q != -1) { int qVertex = cycleNodes[q]; ownerWeight[qVertex] -= K; answer[color[qVertex]] -= K; } } ownedTree[u] = K; answer[color[u]] += K; // Update free() on exactly the affected ancestor path. delta.add(tin[a[u]], -K); if (parentIsTree) { // Cancel the change above p, but retain the change at p. delta.add(tin[a[p]], K); } else { // The cycle root's weight decreases by K. cycleWeights.add(rootPosition, -K); } ancestorQuery.update(tin[u], tout[u], keyOf(u)); }; auto activateCycle = [&](int u) { int cid = component[u]; int b = base[cid]; int e = b + cycleLength[cid]; int position = cycleIndex[u]; int first = firstActive(cid); if (first == -1) { // This is the first active party on this cycle. ll total = cycleWeights.rangeSum(b, e - 1); ownerWeight[u] = total; answer[color[u]] += total; } else { int last = lastActive(cid); auto lower = activeCycle.lower_bound(position); int successor; if (lower != activeCycle.end() && *lower < e) { successor = *lower; } else { successor = first; } int predecessor; if (lower != activeCycle.begin()) { auto previous = prev(lower); predecessor = (*previous >= b ? *previous : last); } else { predecessor = last; } ll transferred = arcSum(cid, predecessor, position); int successorVertex = cycleNodes[successor]; ownerWeight[successorVertex] -= transferred; answer[color[successorVertex]] -= transferred; ownerWeight[u] = transferred; answer[color[u]] += transferred; } activeCycle.insert(position); ancestorQuery.update(tin[u], tout[u], keyOf(u)); }; for (int night = 0; night < M; ++night) { int c; char type; cin >> c >> type; int newColor = (type == 'C' ? 0 : (type == 'O' ? 1 : 2)); if (!active[c]) { active[c] = true; color[c] = newColor; if (onCycle[c]) { activateCycle(c); } else { activateTree(c); } } else if (color[c] != newColor) { ll count = onCycle[c] ? ownerWeight[c] : ownedTree[c]; answer[color[c]] -= count; answer[newColor] += count; color[c] = newColor; } cout << answer[0] << ' ' << answer[1] << ' ' << answer[2] << '\n'; } return 0; }