#include <stdio.h>
#include <vector>
#include <algorithm>
#define ll long long

struct candy {
    ll amount;
    int cnt;
};

int n, m, k, swe[30010], visit[30010], cnt;
ll canDY, DT[3010];
std::vector<int> v[30010];
std::vector<candy> child;

void dfs(int u) {
    cnt++; canDY+=swe[u]; visit[u]=1;
    for(int j=0; j<v[u].size(); j++) {
        if(!visit[v[u][j]]) dfs(v[u][j]);
    }
}
bool cmp(candy A, candy B) {
    double dA=(double)A.amount/A.cnt, dB=(double)B.amount/B.cnt;
    if(dA!=dB) return dA>dB;
    return A.cnt<B.cnt;
}

int main() {
    scanf("%d %d %d", &n, &m, &k);
    for(int i=1; i<=n; i++) scanf("%d", &swe[i]);
    for(int i=0; i<m; i++) {
        int a, b;
        scanf("%d %d", &a, &b);
        v[a].push_back(b);
        v[b].push_back(a);
    }

    for(int i=1; i<=n; i++) {
        if(!visit[i]) {
            cnt=0; canDY=0;
            dfs(i);
            child.push_back({canDY, cnt});
        }
    }

    std::sort(child.begin(), child.end(), cmp);

    for(int i=0; i<child.size(); i++) {
        for(int j=k-1; j>=0; j--) {
            if(j>=child[i].cnt)
                DT[j]=std::max(DT[j], DT[j-child[i].cnt]+child[i].amount);
        }
    }

    printf("%lld ", DT[k-1]);

} 

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: