fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. //function to calculate the points collected in the path
  5. int dfs(int x, vector<vector<int>> &arr, vector<bool> &vis, vector<int> &weight){
  6. int points_max = 0 ;
  7. int points = 0 ;
  8. vis[x] = true ;
  9.  
  10. for(auto &i: arr[x]){
  11. if(!vis[i]){
  12. points = dfs(i, arr, vis, weight) ;
  13. }
  14. points_max = max(points_max, points) ;
  15. }
  16.  
  17. return weight[x] + points_max ;
  18. }
  19.  
  20. int main() {
  21.  
  22. // input starts
  23.  
  24. int N ;
  25. cin >> N ;
  26.  
  27. vector<vector<int>> arr(N + 1) ;
  28.  
  29. vector<bool> vis(N + 1, false) ;
  30.  
  31. vector<int> weight(N + 1) ;
  32.  
  33. vector<int> ans ;
  34.  
  35. for(int i = 1; i <= N; ++i)cin >> weight[i] ;
  36.  
  37. int u, v;
  38.  
  39. for(int i = 0; i < N - 1; ++i){
  40. cin >> u >> v ;
  41. arr[u].push_back(v) ;
  42. arr[v].push_back(u) ;
  43. }
  44.  
  45. // input ends here
  46.  
  47. vis[1] = true ;
  48.  
  49. for(auto &x: arr[1]){
  50. ans.push_back(dfs(x, arr, vis, weight)) ;
  51. }
  52.  
  53. sort(ans.begin(), ans.end(), greater<int>()) ;
  54.  
  55.  
  56. // if only 1 node & 0 edges
  57. if(ans.size() == 0){
  58. cout << weight[1] ;
  59. }
  60. // if only 2 node nodes & 1 edge
  61. else if(ans.size() == 1){
  62. cout << weight[1] + ans[0] ;
  63. }
  64. else{
  65. cout << ans[0] + ans[1] + weight[1] ;
  66. }
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0.01s 5544KB
stdin
3
10 20 30
1 2
2 3
stdout
60