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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include<bits/stdc++.h> #define fo(i,a,b) for(int i=a;i<=b;i++) #define fd(i,a,b) for(int i=a;i>=b;i--) using namespace std;
typedef long long LL;
const int maxn=1e5+5, MX=17;
int n; LL a[maxn]; vector<int> e[maxn];
int Log[maxn]; LL nmin[MX+2][maxn]; void rmq_pre() { fo(i,0,n-1) nmin[0][i]=a[i]; fo(i,2,n) Log[i]=Log[i>>1]+1; fo(j,1,MX) fo(i,0,n-1) nmin[j][i]=min(nmin[j-1][i],nmin[j-1][i+(1<<(j-1))]); } LL rmq(int l,int r) { int t=Log[r-l+1]; return min(nmin[t][l],nmin[t][r-(1<<t)+1]); }
int deepest[maxn],lson[maxn],st[maxn],en[maxn],tot; void dfs_link(int k,int last,int deep) { deepest[k]=deep; for(int son:e[k]) if (son!=last) { dfs_link(son,k,deep+1); if (deepest[son]>deepest[lson[k]]) lson[k]=son; deepest[k]=max(deepest[k],deepest[son]); } } int dfs_index(int k,int last) { st[k]=en[k]=++tot; if (lson[k]) en[k]=dfs_index(lson[k],k); for(int son:e[k]) if (son!=last && son!=lson[k]) dfs_index(son,k); return en[k]; }
LL f[maxn]; int tag[maxn]; void dfs(int k,int last,int deep) { if (lson[k]) dfs(lson[k],k,deep+1); f[st[k]]=a[0]; tag[st[k]]=0; int sondeepest=0; for(int son:e[k]) if (son!=last && son!=lson[k]) { dfs(son,k,deep+1); sondeepest=max(sondeepest,deepest[son]); } fo(i,deep,sondeepest) { int index=st[k]+i-deep; f[index]=min(f[index],rmq(tag[index],i-deep)); tag[index]=i-deep; } for(int son:e[k]) if (son!=last && son!=lson[k]) { fo(i,deep+1,deepest[son]) { int sonindex=st[son]+i-(deep+1); f[sonindex]=min(f[sonindex],rmq(tag[sonindex],i-deep)); f[st[k]+i-deep]+=f[sonindex]; } } }
int main() { int T; scanf("%d",&T); while (T--) { scanf("%d",&n); fo(i,1,n) { scanf("%lld",&a[i-1]); e[i].clear(); } fo(i,2,n) { int u,v; scanf("%d %d",&u,&v); e[u].push_back(v), e[v].push_back(u); }
rmq_pre(); tot=0; memset(lson,0,(n+2)*sizeof(int)); dfs_link(1,0,1); dfs_index(1,0);
memset(f,0,(n+2)*sizeof(LL)); memset(tag,0,(n+2)*sizeof(int)); dfs(1,0,1);
LL ans=0; fo(i,1,deepest[1]) { f[i]=min(f[i],rmq(tag[i],i-1)); ans+=f[i]; }
printf("%lld\n",ans); } }
|