#include<bits/stdc++.h> using namespace std; #define f first #define s second #define sz(s) (int)s.size() #define all(s) s.begin(), s.end() #define pb push_back #define vi vector<int> #define ll long long #define ii pair<int, int> #define vi vector<int> #define vii vector<ii> #define vvi vector<vi> ll suma[301]; ll rep[301]; int Find(int x){ return x == rep[x] ? x : rep[x] = Find(rep[x]); } int main(){ ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; for(int test = 1; test <= t; test++){ int n; cin >> n; vi koszt(n); for(int i = 0; i < n; i++) cin >> koszt[i]; vii kraw; for(int i = 1; i < n; i++){ int a, b; cin >> a >> b; a--, b--; kraw.pb({a, b}); } vector<ll> ans(n, 1e18); for(int i = 0; i < (1 << sz(kraw)); i++){ for(int j = 0; j < n; j++){ suma[j] = koszt[j]; rep[j] = j; } for(int j = 0; j < sz(kraw); j++){ if(i & (1 << j)){ int a = kraw[j].f; int b = kraw[j].s; a = Find(a); b = Find(b); suma[a] += suma[b]; rep[b] = a; } } ll wyn = 0; for(int j = 0; j < n; j++) if(Find(j) == j) wyn += suma[j] * suma[j]; int bity = n - 1 - __builtin_popcount(i); ans[bity] = min(ans[bity], wyn); } for(int i = 0; i < n; i++) cout << ans[i] << ' '; cout << '\n'; } }
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 76 77 78 79 80 81 | #include<bits/stdc++.h> using namespace std; #define f first #define s second #define sz(s) (int)s.size() #define all(s) s.begin(), s.end() #define pb push_back #define vi vector<int> #define ll long long #define ii pair<int, int> #define vi vector<int> #define vii vector<ii> #define vvi vector<vi> ll suma[301]; ll rep[301]; int Find(int x){ return x == rep[x] ? x : rep[x] = Find(rep[x]); } int main(){ ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; for(int test = 1; test <= t; test++){ int n; cin >> n; vi koszt(n); for(int i = 0; i < n; i++) cin >> koszt[i]; vii kraw; for(int i = 1; i < n; i++){ int a, b; cin >> a >> b; a--, b--; kraw.pb({a, b}); } vector<ll> ans(n, 1e18); for(int i = 0; i < (1 << sz(kraw)); i++){ for(int j = 0; j < n; j++){ suma[j] = koszt[j]; rep[j] = j; } for(int j = 0; j < sz(kraw); j++){ if(i & (1 << j)){ int a = kraw[j].f; int b = kraw[j].s; a = Find(a); b = Find(b); suma[a] += suma[b]; rep[b] = a; } } ll wyn = 0; for(int j = 0; j < n; j++) if(Find(j) == j) wyn += suma[j] * suma[j]; int bity = n - 1 - __builtin_popcount(i); ans[bity] = min(ans[bity], wyn); } for(int i = 0; i < n; i++) cout << ans[i] << ' '; cout << '\n'; } } |