1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <limits>
using namespace std;

struct Edge{
    int tar, id;
};

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

    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;
        vector<int>A(n+1);
        for(int i=1;i<=n;i++)
            cin >> A[i];
        
        vector<vector<Edge>>G(n+1);
        for(int i=1;i<n;i++){
            int a, b;
            cin >> a >> b;
            G[a].push_back(Edge{b, i-1});
            G[b].push_back(Edge{a, i-1});
        }

        vector<bool>Removed(n-1);
        vector<bool>Used(n+1);
        function<int(int)> dfs = [&](int v)->int{
            Used[v]=true;
            int sum=A[v];
            for(Edge e : G[v])
                if(!Removed[e.id] && !Used[e.tar])
                    sum += dfs(e.tar);
            return sum;
        };

        vector<long long>Results(n+1, numeric_limits<long long>::max());
        do{
            long long result=0;
            int cnt=0;
            fill(Used.begin(), Used.end(), false);
            for(int i=1;i<=n;i++)
                if(!Used[i]){
                    long long r = dfs(i);
                    result += r*r;
                    cnt++;
                }
            Results[cnt] = min(Results[cnt], result);
            
            int i;
            for(i=0;i<n-1;i++)
                if(Removed[i])
                    Removed[i]=false;
                else{
                    Removed[i]=true;
                    break;
                }
            if(i==n-1)
                break;
        }while(true);

        for(int i=1;i<=n;i++)
            cout << Results[i] << " ";
        cout << "\n";
    }

    return 0;
}