题目 › usaco-1545

COW Traversals

USACO 2026 First · 金组 · 2026-01 · L3 困难 · C++17 · 时限 2 秒 · 测试点等分

查看原题跳到结果

题面

来源: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

auto(max)

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

auto(high)

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

auto(max)

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 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。

代码

Kimi K3.1 Pro · 采样 1 · 349 行
#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;
}