fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. using ll = long long;
  4. int main() {
  5. int t;
  6. cin>>t;
  7.  
  8. while(t--){
  9. int n;
  10. cin>>n;
  11.  
  12. vector<int>a(n);
  13. for(int i = 0 ;i<n;i++)cin>>a[i];
  14.  
  15. vector<vector<ll>>adj(n);
  16.  
  17. for(int i = 1; i< n ;i++){
  18. ll x,y;
  19. cin>>x>>y;
  20.  
  21. x--;
  22. y--;
  23.  
  24. adj[x].push_back(y);
  25. adj[y].push_back(x);
  26. }
  27.  
  28. ll ans = 0;
  29. vector<ll>sz(n,1);
  30.  
  31. function <void(ll,ll)>dfs=[&](ll u,ll par){
  32. vector<ll>val;
  33. for(auto &z :adj[u]){
  34. if(z!=par){
  35. dfs(z,u);
  36. val.push_back(sz[z]);
  37. sz[u]+=sz[z];
  38. }
  39. }
  40.  
  41. val.push_back(n-sz[u]);
  42. assert(accumulate(val.begin(),val.end(),0)==n-1);
  43. if((ll)sqrtl(a[u])*(ll)sqrtl(a[u])<a[u])return;
  44.  
  45. ll pairs = 0;
  46. ll tri = 0;
  47. ll sum = 0;
  48.  
  49. for(auto &z: val){
  50. tri+=pairs*z;
  51. pairs+=sum*z;
  52. sum+=z;
  53. }
  54. ans+=pairs;
  55. ans+=tri;
  56.  
  57. };
  58. dfs(0,-1);
  59. cout<<"ans : "<<ans<<endl;
  60. }
  61. return 0;
  62. }
Success #stdin #stdout 0s 544KB
stdin
4
5
1 1 1 1 1
1 2
2 3
2 4
4 5
10
1 2 3 4 5 6 7 8 9 10
1 3
2 6
6 7
5 4
8 3
3 4
4 6
9 1
10 2
6
12 6 3 18 9 2
3 4
4 5
2 6
6 1
4 2
8
3 16 9 1 8 16 4 9
2 1
3 1
4 3
3 5
6 3
4 7
8 1
stdout
ans : 10
ans : 48
ans : 0
ans : 40