/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 540.0 KiB
#2 Accepted 1ms 540.0 KiB
#3 Accepted 63ms 852.0 KiB
#4 Accepted 61ms 840.0 KiB
#5 Accepted 83ms 952.0 KiB
#6 Accepted 105ms 988.0 KiB
#7 Accepted 106ms 892.0 KiB
#8 Accepted 148ms 3.066 MiB
#9 Accepted 156ms 3.02 MiB
#10 Accepted 151ms 3.969 MiB
#11 Time Exceeded ≥2062ms ≥13.461 MiB
#12 Time Exceeded ≥2056ms ≥31.926 MiB

Code

#include <bits/stdc++.h>

using i64 = long long;

using B = std::bitset<100000>;

void solve() {
    int n;
    std::cin >> n;
    std::vector<int> a(n);
    for (int i = 0; i < n; i++) {
        std::cin >> a[i];
        a[i]--;
    }
    std::vector<std::vector<int>> g(n);
    std::vector<int> size(n);
    for (int i = 0; i < n - 1; i++) {
        int u, v;
        std::cin >> u >> v;
        u--;
        v--;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    std::vector<int> hson(n);
    auto build = [&](auto&& self, int v, int fa) -> int {
        int sz = 1, hsz = 0, hs = -1;
        for (auto w : g[v]) {
            if (w != fa) {
                int s = self(self, w, v);
                sz += s;
                if (s > hsz) {
                    hsz = s;
                    hs = w;
                }
            }
        }
        hson[v] = hs;
        size[v] = sz;
        return sz;
    };
    build(build, 0, -1);

    std::vector<int> ans(n);
    auto f = [&](auto&& self, int v, int fa) -> std::set<int> {
        if (hson[v] < 0) {
            if (a[v] != 0) {
                ans[v] = 1;
            }
            return std::set<int>{a[v]};
        }
        std::set<int> has = self(self, hson[v], v);
        for (auto w : g[v]) {
            if (w != fa && w != hson[v]) {
                std::set<int> subM = self(self, w, v);
                for (auto key : subM) {
                    has.insert(key);
                }
            }
        }
        has.insert(a[v]);
        ans[v] = size[v];
        for (auto key : has) {
            if (key >= size[v]) {
                break;
            }
            ans[v]--;
        }
        return has;
    };

    f(f, 0, -1);
    int q;
    std::cin >> q;
    while (q--) {
        int x;
        std::cin >> x;
        x--;
        std::cout << ans[x] << "\n";
    }

}

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);

    int t;
    std::cin >> t;
    while (t--) {
        solve();
    }
}

Information

Submit By
Type
Submission
Problem
P1157 Roy and Tree Permutation
Contest
Happy New Year 2025
Language
C++17 (G++ 13.2.0)
Submit At
2025-01-02 15:28:43
Judged At
2025-01-02 15:28:43
Judged By
Score
50
Total Time
≥2062ms
Peak Memory
≥31.926 MiB