답안 #854607

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
854607 2023-09-28T06:56:39 Z vjudge1 Sjekira (COCI20_sjekira) C++17
0 / 110
33 ms 5984 KB
//author: Ahmet Alp Orakci
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;

struct DSU {
    int n;
    vector <int> par;
    vector <int> vals;

    DSU(int n) : n(n) {
        par.resize(n +5);
        vals.resize(n +5);
        iota(par.begin(), par.end(), 0ll);
    } 

    inline void build(vector <int> &vec) {
        for(int i = 1; i <= n; i++) {
            vals[i] = vec[i];
        }
    }

    inline int get(int a) {
        return par[a] = (par[a] == a ? a : get(par[a]));
    }

    inline bool same(int a, int b) {
        return get(a) == get(b);
    }

    inline bool unite(int a, int b) {
        if(same(a, b))
            return false;

        par[a] = b;
        vals[b] = max(vals[b], vals[a]);

        return true;
    }

    inline int val(int a) {
        return vals[get(a)];
    }
};

#define ONLINE_JUDGE
void solve() {
    int n;
    cin >> n;

    vector <int> vec(n +1);
    for(int i = 1; i <= n; i++)
        cin >> vec[i];

    vector <int> adj[n +1];
    for(int i = 1; i <= n -1; i++) {
        int u, v;
        cin >> u >> v;

        adj[u].emplace_back(v);
        adj[v].emplace_back(u);
    }

    DSU dsu(n);
    dsu.build(vec);

    vector <int> inds(n +1);
    iota(inds.begin(), inds.end(), 0ll);
    sort(inds.begin(), inds.end(), [&](int a, int b) -> bool {
        return vec[a] < vec[b];
    });

    vector <bool> activated(n +5, false);

    i64 res = 0;
    for(int i = 1; i <= n; i++) {
        int node = inds[i];
        activated[node] = true;
        int mx = dsu.val(node);
        for(int &child : adj[node]) {
            if(activated[child]) {
                res += 0LL + mx + dsu.val(child);
                dsu.unite(child, node);
            }
        }
    }

    cout << res << "\n";
    
    return;
}

signed main() {
    #ifndef ONLINE_JUDGE
        freopen(".in", "r", stdin);
        freopen(".out", "w", stdout);
    #endif

    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    int t = 1; //cin >> t;
    for(int i = 1; i <= t; i++) {
        solve();
    }

    return 0;
}
# 결과 실행 시간 메모리 Grader output
1 Correct 0 ms 344 KB Output is correct
2 Correct 0 ms 348 KB Output is correct
3 Incorrect 0 ms 348 KB Output isn't correct
4 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Incorrect 33 ms 5984 KB Output isn't correct
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Correct 0 ms 344 KB Output is correct
2 Correct 0 ms 348 KB Output is correct
3 Incorrect 0 ms 348 KB Output isn't correct
4 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Correct 0 ms 344 KB Output is correct
2 Correct 0 ms 348 KB Output is correct
3 Incorrect 0 ms 348 KB Output isn't correct
4 Halted 0 ms 0 KB -