Advertisement
Guest User

Untitled

a guest
Mar 10th, 2016
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.69 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define gcd __gcd
  3. #define bitcount __builtin_popcountll
  4. #define rep(i,j,n) for(i=j;i<n;i++)
  5. #define tr(it,c) for(auto it=(c).begin();it!=(c).end();it++)
  6. #define pb push_back
  7. #define mp make_pair
  8. #define hell 1000000007
  9. #define uset unordered_set
  10. #define umap unordered_map
  11. #define ft first
  12. #define sc second
  13. using namespace std;
  14. typedef long long ll;
  15. typedef pair<ll,ll> pl;
  16.  
  17. template <class T> T& get(T &n) {
  18. cin>>n;
  19. return n;
  20. }
  21.  
  22. struct edge{
  23. int n[2];
  24. inline int& operator[](int i){
  25. assert(i==0 || i==1);
  26. return n[i];
  27. }
  28. };
  29.  
  30. struct Tree{
  31. int N;
  32. vector<ll> a;
  33. vector<edge> e;
  34. vector<vector<int>> adj;
  35. vector<vector<pl>> dp;
  36. vector<vector<ll>> dp2;
  37. Tree(int N):N(N),a(N),e(N-1),adj(N),dp(N-1,vector<pl>(2,mp(-1LL,-1LL))),dp2(N-1,vector<ll>(2,-1LL)){
  38. }
  39. ll solve(int i,int idx){ // returns best but computes both best and second best
  40. int u=e[i][idx];
  41. auto ref=&dp[i][idx];
  42. if(*ref==mp(-1LL,-1LL)){
  43. priority_queue<ll,vector<ll>,greater<ll>> q;
  44. for(auto j:adj[u]){
  45. if(i==j) continue;
  46. int v=e[j][0]^e[j][1]^u;
  47. ll p=solve(j,(e[j][0]==v?0:1));
  48. q.push(p);
  49. if(q.size()>2) q.pop();
  50. }
  51. q.push(0);q.push(0);
  52. while(q.size()>2) q.pop();
  53. ref->sc=q.top()+a[u];q.pop();
  54. ref->ft=q.top()+a[u];q.pop();
  55. }
  56. return ref->ft;
  57. }
  58. ll solve2(int i,int idx){
  59. int u=e[i][idx];
  60. auto ref=&dp2[i][idx];
  61. if(*ref==-1LL){
  62. ll ans=dp[i][idx].ft+dp[i][idx].sc-a[u];
  63. for(auto j:adj[u]){
  64. if(i==j) continue;
  65. int v=e[j][0]^e[j][1]^u;
  66. ll p=solve2(j,(e[j][0]==v?0:1));
  67. ans=max(p,ans);
  68. }
  69. *ref=ans;
  70. }
  71. return *ref;
  72. }
  73. ll solve3(){
  74. ll ans=0;
  75. for(int i=0;i<N-1;i++){
  76. ans=max(ans,dp2[i][0]+dp2[i][1]);
  77. }
  78. return ans;
  79. }
  80. };
  81.  
  82. int main() {
  83. int N,i;
  84. ios::sync_with_stdio(0);
  85. cin.tie(0);
  86. cout.tie(0);
  87. cin>>N;
  88. Tree t(N);
  89. rep(i,0,N){
  90. get(t.a[i]);
  91. }
  92. rep(i,0,N-1){
  93. int u=--get(t.e[i][0]);
  94. int v=--get(t.e[i][1]);
  95. t.adj[u].push_back(i);
  96. t.adj[v].push_back(i);
  97. }
  98. rep(i,0,N-1){
  99. t.solve(i,0);
  100. t.solve(i,1);
  101. }
  102. rep(i,0,N-1){
  103. t.solve2(i,0);
  104. t.solve2(i,1);
  105. }
  106. cout<<t.solve3()<<endl;
  107. return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement