diff --git "a/\355\203\201\354\204\261\352\261\264/week31/20303-\355\225\240\353\241\234\354\234\210\354\235\230 \354\226\221\354\225\204\354\271\230_baekjoon.cpp" "b/\355\203\201\354\204\261\352\261\264/week31/20303-\355\225\240\353\241\234\354\234\210\354\235\230 \354\226\221\354\225\204\354\271\230_baekjoon.cpp" new file mode 100644 index 0000000..b99c6b4 --- /dev/null +++ "b/\355\203\201\354\204\261\352\261\264/week31/20303-\355\225\240\353\241\234\354\234\210\354\235\230 \354\226\221\354\225\204\354\271\230_baekjoon.cpp" @@ -0,0 +1,74 @@ +#include +#include +#include +using namespace std; + +struct UnionFind { + vector parent; + vector cnt; + vector candy; + + UnionFind(int sz) : + parent(vector(sz, -1)), + cnt(vector(sz, 1)), + candy(vector(sz)) {} + + int Find(int x) { + if (parent[x] == -1) return x; + return parent[x] = Find(parent[x]); + } + + void Union(int a, int b) { + int pa = Find(a); + int pb = Find(b); + + if (pa == pb) return; + + parent[pb] = pa; + + cnt[pa] += cnt[pb]; + cnt[pb] = 0; + + candy[pa] += candy[pb]; + candy[pb] = 0; + } +}; + +int main(void) { + cin.tie(nullptr)->sync_with_stdio(false); + + int N, M, K; + cin >> N >> M >> K; + + UnionFind uf(N); + + for (auto& c : uf.candy) + cin >> c; + + for (int i = 0; i < M; ++i) { + int u, v; + cin >> u >> v; + uf.Union(u - 1, v - 1); + } + + vector groupCnt; + vector groupCandy; + + for (int i = 0; i < N; ++i) { + if (uf.parent[i] != -1) + continue; + + groupCnt.push_back(uf.cnt[i]); + groupCandy.push_back(uf.candy[i]); + } + + vector dp(K); + + for (int idx = 0; idx < groupCnt.size(); ++idx) + for (int cnt = K - 1; cnt >= groupCnt[idx]; --cnt) + dp[cnt] = max(dp[cnt], dp[cnt - groupCnt[idx]] + groupCandy[idx]); + + cout << dp[K - 1] << '\n'; + + return 0; +}