#include<cstdio> #include<algorithm> #include<vector> #define S 307 using namespace std; typedef long long ll; vector < pair < int, int > > V[S]; ll T[S]; ll odp[S]; ll moc[S]; int sp[S]; void DFS(int x, int nr, int mask){ sp[x] = nr; for(int i = 0 ; i < V[x].size();i++){ int v = V[x][i].first; int y = V[x][i].second; int p = mask & (1<<(y-1)); if( p == 0 && sp[v] == 0){ DFS(v,nr,mask); } } } int main(void){ int z; scanf("%d",&z); while(z--){ int n; scanf("%d",&n); for(int i = 1; i <= n;i++){ scanf("%lld",&T[i]); V[i].clear(); odp[i] = 1e18; } odp[0] = 1e18; for(int i = 1,a,b; i <= n-1;i++){ scanf("%d %d",&a,&b); V[a].push_back({b,i}); V[b].push_back({a,i}); } for(int i = 0; i < (1 << (n-1));i++){ for(int j = 1; j <= n;j++){ sp[j] = 0; moc[j] = 0; } int nr = 0; for(int j = 1; j <= n;j++){ if(sp[j] == 0){ nr++; DFS(j,nr,i); } } for(int j = 1; j <= n;j++){ moc[sp[j]] += T[j]; } ll p = 0; for(int j = 1; j <= n;j++){ p += moc[j]*moc[j]; } int x = i; int lic = 0; while(x != 0){ if(x%2 == 1) lic++; x /= 2; } odp[lic] = min(odp[lic],p); } for(int i = 1; i <= n;i++){ printf("%lld ",odp[i-1]); } printf("\n"); } return 0; }
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 82 83 84 | #include<cstdio> #include<algorithm> #include<vector> #define S 307 using namespace std; typedef long long ll; vector < pair < int, int > > V[S]; ll T[S]; ll odp[S]; ll moc[S]; int sp[S]; void DFS(int x, int nr, int mask){ sp[x] = nr; for(int i = 0 ; i < V[x].size();i++){ int v = V[x][i].first; int y = V[x][i].second; int p = mask & (1<<(y-1)); if( p == 0 && sp[v] == 0){ DFS(v,nr,mask); } } } int main(void){ int z; scanf("%d",&z); while(z--){ int n; scanf("%d",&n); for(int i = 1; i <= n;i++){ scanf("%lld",&T[i]); V[i].clear(); odp[i] = 1e18; } odp[0] = 1e18; for(int i = 1,a,b; i <= n-1;i++){ scanf("%d %d",&a,&b); V[a].push_back({b,i}); V[b].push_back({a,i}); } for(int i = 0; i < (1 << (n-1));i++){ for(int j = 1; j <= n;j++){ sp[j] = 0; moc[j] = 0; } int nr = 0; for(int j = 1; j <= n;j++){ if(sp[j] == 0){ nr++; DFS(j,nr,i); } } for(int j = 1; j <= n;j++){ moc[sp[j]] += T[j]; } ll p = 0; for(int j = 1; j <= n;j++){ p += moc[j]*moc[j]; } int x = i; int lic = 0; while(x != 0){ if(x%2 == 1) lic++; x /= 2; } odp[lic] = min(odp[lic],p); } for(int i = 1; i <= n;i++){ printf("%lld ",odp[i-1]); } printf("\n"); } return 0; } |