fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct node{
  5. vector<int> child;
  6. int req=-1;
  7. };
  8.  
  9. node nodes[20000];
  10. void build(int root){
  11. if(!nodes[root].child.empty()){
  12. for(int i=0;i<nodes[root].child.size();i++){
  13. build( nodes[root].child[i] );
  14. nodes[root].req+= nodes[ nodes[root].child[i] ].req;
  15. }
  16. }
  17. }
  18. int total=0;
  19. void apple(int root){
  20. if( !nodes[root].child.empty() ){
  21. for(int i=0;i<nodes[root].child.size();i++){
  22. total+=abs( nodes[ nodes[root].child[i] ].req);
  23. //cout<<"root: "<<root<<", "<<total<<"\n";
  24. apple( nodes[root].child[i]);
  25.  
  26. }
  27. }
  28. }
  29. int main(){
  30. int n,tmp,m;
  31. cin>>n;
  32.  
  33. int roots[20000];
  34. for(int i=0;i<=n;i++) roots[i]=-1;
  35. for(int i=1;i<=n;i++){
  36. cin>>tmp;
  37. cin>>tmp;
  38. nodes[i].req+=tmp;
  39. cin>>m;
  40. for(int j=0;j<m;j++){
  41. cin>>tmp;
  42. nodes[i].child.push_back(tmp);
  43. roots[tmp]=i;
  44. }
  45. }
  46. int root;
  47. for(int i=1;i<=n;i++){
  48. if(roots[i]==-1) root = i;
  49. }
  50. /*
  51.   for(int i=1;i<=n;i++){
  52.   cout<<roots[i]<<" ";
  53.   }
  54.   cout<<"\n";
  55.   */
  56. //recursion to build tree
  57. for(int i=1;i<=n;i++){
  58. //cout<<i<<": "<<nodes[i].req<<"\n";
  59. }
  60. build( root );
  61. //cout<<"after: \n";
  62. for(int i=1;i<=n;i++){
  63. // cout<<i<<": "<<nodes[i].req<<"\n";
  64. }
  65. apple(root);
  66. cout<<total<<"\n";
  67. }
Success #stdin #stdout 0s 5308KB
stdin
9
1 2 3 2 3 4
2 1 0
3 0 2 5 6
4 1 3 7 8 9
5 3 0
6 0 0
7 0 0
8 2 0
9 0 0
stdout
7