Advertisement
MarioYC

Selectivo 2 - P6

Sep 2nd, 2012
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <cstdio>
  2. #include <algorithm>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. #define MAXN 500000
  8.  
  9. vector<int> L[MAXN],W[MAXN];
  10. int best[MAXN][2];
  11.  
  12. void fix(int x){
  13.     if(best[x][1] > best[x][0])
  14.         swap(best[x][0],best[x][1]);
  15. }
  16.  
  17. int ans;
  18.  
  19. void dfs(int cur, int p){
  20.     best[cur][0] = best[cur][1] = -500000000;
  21.    
  22.     for(int i = L[cur].size() - 1,to;i >= 0;--i){
  23.         to = L[cur][i];
  24.        
  25.         if(to != p){
  26.             dfs(to,cur);
  27.            
  28.             int aux = W[cur][i] + max(best[to][0],0);
  29.            
  30.             if(aux > best[cur][1]){
  31.                 best[cur][1] = aux;
  32.                 fix(cur);
  33.             }
  34.         }
  35.     }
  36.    
  37.     ans = max(ans,best[cur][0] + best[cur][1]);
  38.     ans = max(ans,best[cur][0]);
  39. }
  40.  
  41. int main(){
  42.     int n;
  43.    
  44.     while(true){
  45.         scanf("%d",&n);
  46.         if(n == 0) break;
  47.        
  48.         for(int i = 0;i < n;++i){
  49.             L[i].clear();
  50.             W[i].clear();
  51.         }
  52.        
  53.         for(int i = 1,u,p;i < n;++i){
  54.             scanf("%d %d",&u,&p);
  55.            
  56.             L[i].push_back(u);
  57.             W[i].push_back(p);
  58.            
  59.             L[u].push_back(i);
  60.             W[u].push_back(p);
  61.         }
  62.        
  63.         ans = 0;
  64.         dfs(0,-1);
  65.        
  66.         printf("%d\n",ans);
  67.     }
  68.    
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement