/ SeriousOJ /

Record Detail

Wrong Answer


  
# Status Time Cost Memory Cost
#1 Wrong Answer 1ms 584.0 KiB
#2 Wrong Answer 2ms 584.0 KiB

Code

#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>

using namespace std;

void dfs(int node, int parent, const vector<vector<int>>& tree, vector<int>& nodes) {
    nodes.push_back(node);
    for (int neighbor : tree[node]) {
        if (neighbor != parent) {
            dfs(neighbor, node, tree, nodes);
        }
    }
}

int minChangesToPermutation(const vector<int>& nodes, const vector<int>& values) {
    int S = nodes.size();
    vector<int> count(S + 1, 0);

    for (int node : nodes) {
        int value = values[node];
        if (value <= S) {
            count[value]++;
        }
    }

    int changes_needed = 0;
    unordered_set<int> used;
    for (int i = 1; i <= S; ++i) {
        if (count[i] == 0) {
            changes_needed++;
        } else {
            while (count[i] > 1) {
                int replace_val = 1;
                while (used.find(replace_val) != used.end() || count[replace_val] > 0) {
                    replace_val++;
                }
                used.insert(replace_val);
                count[replace_val]++;
                count[i]--;
                changes_needed++;
            }
        }
    }
    return changes_needed;
}

int main() {
    int T;
    cin >> T;

    while (T--) {
        int N;
        cin >> N;

        vector<int> values(N);
        for (int i = 0; i < N; ++i) {
            cin >> values[i];
        }

        vector<vector<int>> tree(N);
        for (int i = 0; i < N - 1; ++i) {
            int u, v;
            cin >> u >> v;
            --u; --v;
            tree[u].push_back(v);
            tree[v].push_back(u);
        }

        int Q;
        cin >> Q;

        vector<int> queries(Q);
        for (int i = 0; i < Q; ++i) {
            cin >> queries[i];
            --queries[i];
        }

        for (int x : queries) {
            vector<int> nodes;
            dfs(x, -1, tree, nodes);

            cout << minChangesToPermutation(nodes, values) << endl;
        }
    }

    return 0;
}

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:36:08
Judged At
2025-01-02 15:36:08
Judged By
Score
0
Total Time
2ms
Peak Memory
584.0 KiB